您的位置:首页 > 编程语言 > Python开发

python paramiko 执行命令

2016-10-28 17:14 183 查看
参考
http://wangwei007.blog.51cto.com/blog/68019/1058726
http://youzao.blog.51cto.com/3946111/1348903
在node1上想对node2执行命令,标准的答案
1.比较直观
#!/usr/bin/env python
import paramiko
hostname='192.168.0.102'
username='root'
password='abc'
port=22
paramiko.util.log_to_file('paramiko.log')
s=paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname = hostname,port=port,username=username, password=password)
stdin,stdout,stderr=s.exec_command('free;df -h')
print stdout.read()
2.类的形式
#!/usr/bin/python
# coding=utf8
import paramiko,datetime,os,threading
#class run_cmd(threading.Thread):
class run_cmd():
def __init__(self,hostname=None,password=None,username=None,port=None,echo_cmd=None):
#threading.Thread.__init__(self)
self.hostname=hostname
self.password=password
self.username=username
self.port=port
self.echo_cmd=echo_cmd
#self.thread_stop=False
def run(self):
paramiko.util.log_to_file('paramiko.log')
s=paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname = self.hostname,username=self.username, password=self.password)
stdin,stdout,stderr=s.exec_command(self.echo_cmd)
return stdout.read()
s.close()
def stop(self):
self.thread_stop=True

if __name__=='__main__':
f = file('/home/python/filelist1','r')
port=22
c = f.readlines()
for x in c:
hostname = x.split('::')[0]
password = x.split('::')[1]
username = x.split('::')[2]
remote = x.split('::')[4].strip('\n')
echo_cmd='/bin/find %s -maxdepth 1 -type d -mmin -1200' %(remote)
#echo_cmd='free;df -h'
cmd_thread=run_cmd(hostname,password,username,port,echo_cmd)
result=cmd_thread.run()
print result
f.close()

如果运行有错误,请参考python 增量同步远程文件夹

2.Python 利用pexpect和paramiko模块进行远程服务器的监控
#!/usr/bin/python# encoding=utf-8# Filename: paramiko_test.pyimport datetimeimport threadingimport paramikodef sshCmd(ip, username, passwd, cmds):
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(ip, 22, username, passwd, timeout=5)        for cmd in cmds:
stdin, stdout, stderr = client.exec_command(cmd)
lines = stdout.readlines()            # print out
for line in lines:                print line,        print '%s\t 运行完毕\r\n' % (ip)    except Exception, e:        print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)    finally:
client.close()#上传文件def uploadFile(ip,username,passwd):
try:
t=paramiko.Transport((ip,22))
t.connect(username=username,password=passwd)
sftp=paramiko.SFTPClient.from_transport(t)
remotepath='/root/main.py'
localpath='/home/data/javawork/pythontest/src/main.py'
sftp.put(localpath,remotepath)        print '上传文件成功'
except Exception, e:        print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)    finally:
t.close()#下载文件def downloadFile(ip,username,passwd):
try:
t=paramiko.Transport((ip,22))
t.connect(username=username,password=passwd)
sftp=paramiko.SFTPClient.from_transport(t)
remotepath='/root/storm-0.9.0.1.zip'
localpath='/home/data/javawork/pythontest/storm.zip'
sftp.get(remotepath,localpath)        print '下载文件成功'
except Exception, e:        print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)    finally:
t.close()

if __name__ == '__main__':    # 需要执行的命令列表
cmds = ['ls /root', 'ifconfig']    # 需要进行远程监控的服务器列表
servers = ['xxx.xxx.xxx.xxx']

username = "root"
passwd = "xxxxxx"
threads = []    print "程序开始运行%s" % datetime.datetime.now()    # 每一台服务器创建一个线程处理
for server in servers:
th = threading.Thread(target=sshCmd, args=(server, username, passwd, cmds))
th.start()
threads.append(th)    # 等待线程运行完毕
for th in threads:
th.join()    print "程序结束运行%s" % datetime.datetime.now()    #测试文件的上传与下载
uploadFile(servers[0],username,passwd)
downloadFile(servers[0],username,passwd)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python