使用密码远程执行命令
[[email protected] script]# cat daramiko_ssh.py #!/usr/bin/env python #_*_coding:utf-8 _*_ __author__ = ‘gaogd‘ import paramiko import sys,os host = sys.argv[1] user = ‘root‘ password = ‘ddfasdsasda2015‘ cmd = sys.argv[2] s = paramiko.SSHClient() #绑定实例 s.load_system_host_keys() #加载本机KONW_HOST主机文件 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()
使用key远程执行命令
[[email protected] script]# cat daramiko_ssh_key.py #!/usr/bin/env python #_*_coding:utf-8 _*_ __author__ = ‘gaogd‘ import paramiko import sys,os host = sys.argv[1] port = 22 username = ‘root‘ pkey_file = ‘/root/.ssh/id_rsa‘ key = paramiko.RSAKey.from_private_key_file(pkey_file) cmd = sys.argv[2] s = paramiko.SSHClient() #绑定实例 s.load_system_host_keys() #加载本机KONW_HOST主机文件 s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(host,port,username,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() [[email protected] script]#
上传下载文件
[[email protected] script]# cat daramiko_sftp.py #!/usr/bin/python import os,sys import paramiko host = ‘192.168.10.11‘ user = ‘root‘ password = ‘[email protected]‘ s = paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) t = paramiko.Transport((host,22)) t.connect(username=user,password=password) #pkey_file = ‘/home/alex/.ssh/id_rsa‘ #key = paramiko.RSAKey.from_private_key_file(pkey_file) #t.connect(username=username,pkey=key) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(‘/root/.ssh/known_hosts‘,‘/tmp/known_hosts1‘) sftp.put(‘/python/script/daramiko_ssh_key.py‘,‘/tmp/paramiko1.py‘) s.close() [[email protected] script]#
时间: 2024-10-21 05:17:24