Python Paramiko模块的安装与使用详解
paramiko是短链接,不是持续链接,只能执行你设定的shell命令,可以加分号执行两次命令。
http://www.111cn.net/phper/python/67973.htm
安装过程排错解决方案
http://blog.csdn.net/wang1144/article/details/42277179
一、python模拟ssh密码登录
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import paramiko
import sys,os
host = '10.74.85.167'
user = 'liqian'
password = '123456'
cmd = 'ls -l'
#绑定实例
s = paramiko.SSHClient()
#加载本机.ssh/knows_hosts文件
s.load_system_host_keys()
#第一次登陆机器需要输入yes,添加完之后就不用输入
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#登录远程主机
s.connect(host,22,user,password,timeout=5)
#远程执行命令
stdin,stdout,stderr = s.exec_command(cmd)
#错误输出和正确输出,两者只有一个输出,要么是正确输出,要么是错误输出
cmd_result = stdout.read(),stderr.read()
#输出的结果逐行打印
for line in cmd_result:
print line
s.close()
二、python模拟ssh免密码登录
需要将.ssh/id_rsa.pub 拷贝到对方机器.ssh/authorized_keys中,使用私钥
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import paramiko
import sys,os
pkey_file = '/root/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pkey_file)
host = '10.74.85.167'
user = 'root'
cmd = 'ls -l'
#绑定实例
s = paramiko.SSHClient()
#加载本机.ssh/knows_hosts文件
s.load_system_host_keys()
#第一次登陆机器需要输入yes,添加完之后就不用输入
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(host,22,user,pkey=key,timeout=5)
stdin,stdout,stderr = s.exec_command(cmd)
cmd_result = stdout.read(),stderr.read()
for line in cmd_result:
print line
s.close()
三、paramiko实现sftp上传下载文件
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import paramiko
import sys,os
host = '10.74.85.167'
user = 'root'
password = '123456'
t = paramiko.Transport((host,22))
t.connect(username=user,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
#sftp.get('/pythonShare/ssh.py','ssh.py.bak') #下载
sftp.put('ssh.py.bak','/tmp/ssh.py') #上传
t.close()