paramiko ssh模块
使用用户名密码连接远程机器
使用用key连接远程机器
远程文件传送
lg:使用用户名密码连接远程机器
import paramiko
import os,sys
host = sys.argv[1] #用来获取命令行参数的
user = 'alex'
password = 'alex123'
cmd = sys.argv[2]
s = paramiko.SSHClient() #绑定实例
s.load_system_host_keys() #加载本机HOST主机文件
#s.set_missing_host_key_policy(paramike.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()
lg:使用用key连接远程机器
import paramiko
pkey_file = '/home/alex/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_file(pkey_file)
s.connect(host,port,username,pkey=key,timeout=5)
stdin,stdout,stderr = s.exec_command(cmd)
lg:远程文件传送
import os,sys
import paramiko
host = 'localhost'
user = 'alex'
password = 'alex123'
s = paramiko.SSHClient() #绑定实例
s.load_system_host_keys() #加载本机HOST主机文件
s.set_missing_host_key_policy(paramike.AutoAddPolicy())
t = paramiko.Transport((host,22))
t.connect(username=user,password=password)
#pkey_file = '/home/alex/.ssh/id_rsa'
#key = paramiko.RSAKey.from_private_file(pkey_file)
#t.connect(host,port,username,pkey=key,timeout=5)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/paramiko1.py','paramiko2.pydd')
sftp.put('paramiko1.py','/tmp/paramiko1.py')
s.close()