python执行shell命令
python执行shell命令,首先需要安装依赖包
1 |
sudo pip install expect |
一个远程复制的python类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class RemoteShell: def __init__(self, host, user, pwd): self.host = host self.user = user self.pwd = pwd def put(self, local_path, remote_path): scp_put = ''' set timeout -1 spawn scp %s %s@%s:%s expect "(yes/no)?" { send "yes\r" expect "password:" send "%s\r" } "password:" {send "%s\r"} expect eof exit''' os.system("echo '%s' > scp_put.cmd" % (scp_put % (os.path.expanduser(local_path), self.user, self.host, remote_path, self.pwd, self.pwd))) os.system('expect scp_put.cmd') os.system('rm scp_put.cmd') |
具体是通过ecpect来捕获shell输出,然后通过send发送命令,执行。可以参照原作者的例子很快的改造出简单的python执行shell命令脚本。也可以使用 pexpect 模块。
原文链接:http://blog.csdn.net/span76/article/details/11575231