【发布时间】:2021-04-15 12:30:58
【问题描述】:
我正在尝试执行 ssh 命令: ssh -t user1@hostname "sudo su - user2 -s /bin/bash"
我下面的代码不起作用:
expectations = [('password', '******')]
cmd = ['ssh','-t','user1@hostname','"','sudo','su','-','user2','-s','/bin/bash', '"']
try:
clean_non_empty_lines = []
expectations = [(None, None)] + expectations
p = subprocess.Popen(cmd,stdin=subprocess.PIPE,stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
bufsize=1)
last_line = None
for expectation, response in expectations:
if expectation is not None:
expectation = re.compile('$(.*)' + expectation + '(.*)')
if expectation is not None and expectation.search(last_line):
stdout, stderr = p.communicate(input=bytes(response, 'utf-8'))
else:
stdout, stderr = p.communicate()
if stderr is not None:
error = str(stderr.decode('ascii')).rstrip()
print(error)
if stdout is not None:
last_line = stdout.decode('utf8')
for line in iter(re.split('\r\n|\n', last_line)):
line = str(line.rstrip())
if line != '':
print(line)
line = line.strip()
if line:
clean_non_empty_lines += [line]
p.stdout.close()
p.wait()
我收到以下错误:
Pseudo-terminal will not be allocated because stdin is not a terminal. sudo: no tty present and no askpass program specified
有没有办法让它工作?这样在执行 sudo su - user2.... 之后程序会使用变量 'expectations' 中指定的密码来响应密码提示?
【问题讨论】:
标签: python python-3.x ssh subprocess