Python子进程sudo返回错误:错误:['sudo:抱歉,你必须有一个tty才能运行sudo\n'] [英] Python subprocess sudo returns error: ERROR: ['sudo: sorry, you must have a tty to run sudo\n']
问题描述
这是我的代码:
import subprocess
HOST = 'host_name'
PORT = '111'
USER = 'user_name'
CMD = 'sudo su - ec2-user; ls'
process = subprocess.Popen(['ssh','{}@{}'.format(USER, HOST),
'-p', PORT, CMD],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = process.stdout.readlines()
if not result:
print "Im an error"
err = process.stderr.readlines()
print('ERROR: {}'.format(err))
else:
print "I'm a success"
print(result)
当我运行它时,我在终端中收到以下输出:
When I run this I receive the following output in my terminal:
dredbounds-computer: documents$ python terminal_test.py
Im an error
ERROR: ['sudo: sorry, you must have a tty to run sudo\n']
我尝试了多种方法,但我一直收到错误sudo:抱歉,您必须有一个 tty 才能运行 sudo".如果我只是通过终端手动完成它,它工作正常,但我需要自动执行此操作.我读到一个解决方法可能是在我的 ssh 调用中使用-t"或-tt",但我还没有能够在子进程中成功实现这个(终端只是挂起我).任何人都知道如何修复我的代码或解决此问题?理想情况下,我想 ssh,然后切换到 sudo 用户,然后从那里运行一个文件(我只是将 ls 用于测试目的).
I've tried multiple things but I keep getting that error "sudo: sorry, you must have a tty to run sudo". It works fine if I just do it through the terminal manually, but I need to automate this. I read that a workaround might be to use '-t' or '-tt' in my ssh call, but I haven't been able to implement this successfully in subprocess yet (terminal just hangs for me). Anyone know how I can fix my code, or work around this issue? Ideally I'd like to ssh, then switch to the sudo user, and then run a file from there (I just put ls for testing purposes).
推荐答案
sudo
提示您输入密码,但它需要一个终端来执行此操作.传递 -t
或 -tt
提供了一个终端供远程命令运行,但现在它正在等待您输入密码.
sudo
is prompting you for a password, but it needs a terminal to do that. Passing -t
or -tt
provides a terminal for the remote command to run in, but now it is waiting for you to enter a password.
process = subprocess.Popen(['ssh','-tt', '{}@{}'.format(USER, HOST),
'-p', PORT, CMD],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
process.stdin.write("password\r\n")
不过请记住,ls
不会运行,直到 after 由 su
启动的 shell 退出.您应该直接以 ec2-user
身份登录机器(如果可能),或者只使用 sudo
运行您想要的任何命令而无需通过 su代码>首先.
Keep in mind, though, that the ls
doesn't run until after the shell started by su
exits. You should either log into the machine as ec2-user
directly (if possible), or just use sudo
to run whatever command you want without going through su
first.
这篇关于Python子进程sudo返回错误:错误:['sudo:抱歉,你必须有一个tty才能运行sudo\n']的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!