python调用shell脚本(commands或subprocess或pexpect)

方法1:

>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

 

方法2:

python3.7中使用subprocess替代commands。

import subprocess
p=subprocess.Popen(["ls","-all"], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
text=p.stdout.read().decode()
err=p.stderr.read().decode()

 

方法3,pexpect:

def ssh_remote_cmd(ip, user, passwd, cmd):
    ret = -1
    ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, ip, cmd))
    try:
        i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
        if i == 0 :
            ssh.sendline(passwd)
        elif i == 1:
            ssh.sendline('yes\n')
            ssh.expect('password: ')
            ssh.sendline(passwd)

        ssh.sendline(cmd)
        r = ssh.read()
        print(r)
        ret = 0
    except pexpect.EOF:
        print("EOF")
        ssh.close()
        ret = -1
    except pexpect.TIMEOUT:
        print("TIMEOUT")
        ssh.close()
        ret = -2
    return ret

你可能感兴趣的:(python调用shell脚本(commands或subprocess或pexpect))