我有这个使用Pexpect的Python3代码。
import pexpect
import getpass
import sys
def ssh(username,password,host,port,command,writeline):
child = pexpect.spawn("ssh -p {} {}@{} '{}'".format(port,username,host,command))
child.expect("password: ")
child.sendline(password)
if(writeline):
print(child.read())
def scp(username,password,host,port,file,dest):
child = pexpect.spawn("scp -P {} {} {}@{}:{}".format(port,file,username,host,dest))
child.expect("password: ")
child.sendline(password)
try:
filename = sys.argv[1]
print("=== sendhw remote commander ===")
username = input("Username: ")
password = getpass.getpass("Password: ")
ssh(username,password,"some.host.net","22","mkdir ~/srakrnSRV",False)
scp(username,password,"some.host.net","22",filename,"~/srakrnSRV")
ssh(username,password,"some.host.net","22","cd srakrnSRV && sendhw {}".format(filename),True)
except IndexError:
print("No homework name specified.")
我的目标是:
ssh
函数通过SSH登录主机,创建目录srakrnSRV
,然后srakrnSRV
目录cd
进入srakrnSRV
,然后执行sendhw <filename>
命令。 filename
变量由命令行参数定义,并打印出结果。运行完整个代码后,Python打印出来
b'\r\nbash: line 0: cd: srakrnSRV: No such file or directory\r\n'
这是不期望的,因为该目录应该先前创建。
另外,我尝试在远程主机中手动创建srakrnSRV
文件夹。再次运行该命令后,似乎scp
功能也未运行。唯一的运行pexpect coomand是最后一个ssh
函数。
如何让它按顺序执行?提前谢谢!
答案 0 :(得分:0)
您可能缺少通过ssh执行命令的权限。此外,您的程序可能会在提示发生之前发送scp。