【python】python 模組學習之--pexpect

小亮520cl發表於2016-08-18

基礎例子:

複製資料
  1. >>> import pexpect
  2. >>> child=pexpect.spawn('scp /home/chenliang/oradba.perl root@218.78.186.162:/home/chenliang/')            -----啟動程式
  3. >>> child.expect('(?i)password:')                                                                          -----匹配密碼,expect正規表示式,表示匹配的意思
  4. 0
  5. >>> child.sendline('XXXXXXXXX')                                                                            ------傳送密碼,sendline 傳送命令
  6. 9
檢查:複製成功
[root@localhost /home/chenliang ]# ls
1.txt  2.txt  oradba.perl  test.txt

ssh目標機器並建立一個檔案
  1. >>> import pexpect
  2. >>> tar=pexpect.spawn('ssh root@218.78.186.162')
  3. >>> tar.expect('(?i)password:')
  4. 0
  5. >>> tar.sendline('ESBecs00')                               ####sendline 傳送密碼
  6. 9
  7. >>> tar.sendline('touch /home/chenliang/tar.txt')          ####sendline 傳送命令
  8. 30
檢查:成功
[root@localhost /home/chenliang ]# ls
1.txt  2.txt  oradba.perl  tar.txt  test.txt

run命令
  1. 和 os.system一樣呼叫系統命令
  2. >>> run('touch /home/chenliang/run.txt')
  3. ''


練習一
  1. ssh並執行命令
    1. [root@hostnfsd :/soft/python]$ more test2.py
    2. #ssh_cmd.py
    3. #coding:utf-8

    4. import pexpect
    5. import sys
    6. ip='218.78.186.162'
    7. user='root'
    8. passwd='XXXXX'
    9. cmd='df -h'
    10. def ssh_cmd(vip,vuser,vpassword,vcmd):
    11.         child=pexpect.spawn('ssh %s@%s %s' % (vuser, vip,vcmd))
    12.         r = ''
    13.         child.expect('(?i)password:')
    14.         child.sendline(vpassword)
    15.         r = child.read()
    16.         return r

    17. print ssh_cmd(ip, user, passwd, cmd)

    [root@hostnfsd :/soft/python]$ python test2.py 
     
    Filesystem            Size  Used Avail Use% Mounted on
    /dev/mapper/VolGroup-lv_root
                           18G   15G  1.7G  90% /
    tmpfs                 1.9G  8.0K  1.9G   1% /dev/shm
    /dev/xvda1            485M  119M  341M  26% /boot
    /dev/mapper/vgu01-lvu01
                           20G  3.2G   16G  17% /home
    /dev/mapper/vgu01-lvu02
                           30G   33M   30G   1% /back


  2. 向多臺機器ssh並執行多個命令
    1. 稍微修改一下就好了
    2. #!/usr/bin/python
      import pexpect


      def ssh_cmd(ip, user, passwd, cmd):
          ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, ip, cmd))
          r = ''
          ssh.expect('(?i)password:')
          ssh.sendline(passwd)
          r = ssh.read()
          return r


      hosts = '''
      218.78.186.162:root:xxxx:df -h,uptime,tar -zcf /home/chenliang/tar.txt.tar.gz  /home/chenliang/tar.txt;
    3. 218.78.186.163:root:xxxx:df -h,uptime,tar -zcf /home/chenliang/tar.txt.tar.gz  /home/chenliang/tar.txt;
      '''


      for host in hosts.split("\n"):
          if host:
              ip, user, passwd, cmds = host.split(":")
              for cmd in cmds.split(","):
                  print "-- %s run:%s --" % (ip, cmd)
                  print ssh_cmd(ip, user, passwd, cmd)


    4. 執行結果
      1. [root@hostnfsd :/soft/python]$ python test1.py
      2. -- 218.78.186.162 run:df -h --
      3.  
      4. Filesystem Size Used Avail Use% Mounted on
      5. /dev/mapper/VolGroup-lv_root
      6.                        18G 15G 1.7G 90% /
      7. tmpfs 1.9G 8.0K 1.9G 1% /dev/shm
      8. /dev/xvda1 485M 119M 341M 26% /boot
      9. /dev/mapper/vgu01-lvu01
      10.                        20G 3.2G 16G 17% /home
      11. /dev/mapper/vgu01-lvu02
      12.                        30G 33M 30G 1% /back

      13. -- 218.78.186.162 run:uptime --
      14.  
      15.  13:28:27 up 57 days, 1 min, 1 user, load average: 0.10, 0.11, 0.03

      16. -- 218.78.186.162 run:tar -zcf /home/chenliang/tar.txt.tar.gz /home/chenliang/tar.txt; --




  3. 更完整版
    1. #ssh_cmd.py
    2. #coding:utf-8

    3. import pexpect

    4. def ssh_cmd(ip, user, passwd, cmd):
    5.     ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, ip, cmd))
    6.     r = ''
    7.     try:
    8.         i = ssh.expect(['password: ', 'continue connecting (yes/no)?'])
    9.         if i == 0 :
    10.             ssh.sendline(passwd)
    11.         elif i == 1:
    12.             ssh.sendline('yes')
    13.     except pexpect.EOF:
    14.         ssh.close()
    15.     else:
    16.         r = ssh.read()
    17.         ssh.expect(pexpect.EOF)
    18.         ssh.close()
    19.     return r

    20. hosts = '''
    21. 218.78.186.162:root:XXXXXX:df -h,uptime,tar -zcf /home/chenliang/tar.txt.tar.gz /home/chenliang/tar.txt;
    22. '''

    23. for host in hosts.split("\n"):
    24.     if host:
    25.         ip, user, passwd, cmds = host.split(":")
    26.         for cmd in cmds.split(","):
    27.             print "-- %s run:%s --" % (ip, cmd)
    28.             print ssh_cmd(ip, user, passwd, cmd)


練習二:

  1. ssh遠端機器 並tar檔案再傳回本地
    1. #!/usr/bin/python
    2. import pexpect
    3. import sys
    4. ip='218.78.186.162'
    5. passwd='XXXXXXX'
    6. user='root'
    7. cmd='gzip /home/chenliang/tar.txt'
    8. source_dir='/home/chenliang/'
    9. def ssh_m(vip,vuser,vpassword,vcmd):
    10.         child=pexpect.spawn('ssh %s@%s %s' % (vuser, vip,vcmd))
    11.         r = ''
    12.         child.expect('(?i)password:')
    13.         child.sendline(vpassword)
    14.         r = child.read()
    15.         child.sendline('exit')
    16.         return r

    17. def scp_m(vip,vuser,vpassword,source_dir):
    18.         child=pexpect.spawn('scp %s@%s:/home/chenliang/tar.txt.gz %s' % (vuser, vip,source_dir))
    19.         r = ''
    20.         child.expect('(?i)password:')
    21.         child.sendline(vpassword)
    22.         r = child.read()
    23.         child.sendline('exit')
    24.         return r

    25. print ssh_m(ip, user, passwd, cmd)
    26. print scp_m(ip, user, passwd,source_dir)


疑問:
  1. [root@hostnfsd :/soft/python]$ more test3.py
  2. #!/usr/bin/python
  3. import pexpect
  4. import sys
  5. ip='218.78.186.162'
  6. user='root'
  7. passwd='ESBecs00'
  8. cmd='touch /home/chenliang/111t'
  9. def ssh_cmd(vip,vuser,vpassword,vcmd):
  10.         child=pexpect.spawn('ssh %s@%s ' % (vuser, vip))        ----####如果將cmd移到下面
  11.         r = ''
  12.         child.expect('(?i)password:')
  13.         child.sendline(vpassword)
  14.         child.sendline('%s'%vcmd)                               ------#####命令移到這個部分,會tm的執行失敗,還不知道為什麼
  15.         r = child.read(
  16.         return r

  17. print ssh_cmd(ip, user, passwd, cmd)

。。。待續

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29096438/viewspace-2123669/,如需轉載,請註明出處,否則將追究法律責任。

相關文章