1、利用密码登录
#!/usr/bin/env python #coding:utf8 import paramiko import sys host = sys.argv[1] user = sys.argv[2] password = sys.argv[3] port = int(sys.argv[4]) cmd = sys.argv[5] if __name__ == "__main__": paramiko.util.log_to_file('/root/test/testssh.log') s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(host,port,user,password) stdin,stdout,stderr=s.exec_command(cmd) print "--------Result from? %s -------" % host print stdout.read() s.close()
执行方式: python testssh.py 192.168.30.76 root password 22 "df -h"
2、利用key登录
#!/usr/bin/env python #coding:utf8 import sys import paramiko host = sys.argv[1] user = sys.argv[2] port = int(sys.argv[3]) cmd = sys.argv[4] if __name__ == "__main__": pkey = '/home/username/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(pkey) s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.load_system_host_keys() s.connect(host,port,user,pkey=key) stdin,stdout,stderr=s.exec_command(cmd) print stdout.read()
运行方式:python testsshkey.py 192.168.80.88 username 22 "df -h"
3、上传文件到远程服务器
#!/usr/bin/env python #coding:utf8 import paramiko import sys if __name__ == "__main__": t = paramiko.Transport(("192.168.30.76",22)) t.connect(username = "root", password = "123abc") sftp = paramiko.SFTPClient.from_transport(t) remotepath='/tmp/testput.py' localpath='/root/test/testput.py' sftp.put(localpath,remotepath) t.close()
4、从远程服务器下载文件到本机
#!/usr/bin/env python #coding:utf8 import paramiko import sys if __name__ == "__main__": t = paramiko.Transport(("192.168.30.76",22)) t.connect(username = "root", password = "123abc") sftp = paramiko.SFTPClient.from_transport(t) remotepath='/tmp/testget.py' localpath='/tmp/testtget.py' sftp.get(localpath,remotepath) t.close()
本文出自 “leboit” 博客,谢绝转载!