234123 发表于 2016-10-27 09:45:56

python paramiko

在node1上想对node2执行命令,标准的答案
1.比较直观

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/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()         
s.close()




2.类的形式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/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('::')
      password = x.split('::')
      username = x.split('::')   
      remote = x.split('::').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()





1
echo_cmd='/bin/find%s -maxdepth 1 -type d -mmin -1200' %(remote)




这个主要为了找node2机器上面最近文件夹更新情况。
页: [1]
查看完整版本: python paramiko