python - Python + Paramiko + 错误:sudo:没有 tty,也没有指定 askpass 程序
问题描述
我已经验证了现有的线程,但无法得到这个问题的确切原因和解决方案。
问题:'sudo: no tty present and no askpass program specified' 当代码如下:
str_command_to_exec += str(each_cmd).strip() + "\n"
# Now execute the command
stdin, stdout, stderr = self.client.exec_command('sudo -S ls')
以下是我已经应用但仍然没有进展的可能解决方案。
Sol:将密码附加到命令。'sudo: 没有 tty,也没有指定 askpass 程序。bash:第 1 行::找不到命令'
Sol2: stdin, stdout, stderr = client.exec_command(command, get_pty=True) 超过 30 秒仍然不知道控制是否从 exec_command(...) 传递过来。
Sol3: self.client.get_pty() 无法建立连接。
溶胶4:
标准输入、标准输出、标准错误 = self.client.exec_command('sudo -S ls') stdin.write('\n') stdin.flush() time.sleep(2)
无法对 sudo 命令 'stdin, stdout, stderr = self.client.exec_command('sudo -S info')' 执行相同操作会导致相同的问题。
如果有任何解决方案来处理 Sudo 命令或变通方法,有人可以指出我吗?
解决方案
我能够得到这个问题的解决方案。
我使用了 send(..) 而不是 execute_command(...)。
设置:
self.client = paramiko.client.SSHClient()
self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
self.client.connect(hostname=self.str_host_name, port=22,
username=self.str_user_name, password=self.str_user_pass)
self.transport = paramiko.Transport(self.str_host_name, 22)
self.transport.connect(username=self.str_user_name, password=self.str_user_pass)
执行:
if self.shell:
self.shell.send(str_sudo_command + "\n")
if self.shell is not None:
time.sleep(2)
self.str_sudo_command_result += str(self.shell.recv(1024).decode('utf-8'))
self.str_sudo_command_result = str(self.str_sudo_command_result).strip()
self.str_sudo_command_result = self.str_sudo_command_result.splitlines()
if len(self.str_sudo_command_result) > 0:
if "[sudo] password for " in self.str_sudo_command_result[-1]:
self.str_sudo_command_result = ""
self.shell.send(self.str_user_pass + "\n")
time.sleep(2)
else:
while True:
result = str(self.str_sudo_command_result)
result = result.splitlines()
time.sleep(2)
if self.str_result_end_line not in result[-1]:
while self.shell.recv_ready():
self.str_sudo_command_result += str(self.shell.recv(9999).decode('utf-8'))
else:
break
欢迎提出建议和指正。
推荐阅读
- c# - 如何在 WMI Win32_Directory 查询的目录名称中转义右花括号 ( } )?
- docker - 如何在 docker compose 的帮助下正确设置 golang 应用的第三方库?
- keras - 神经网络只从二元类中预测一个类
- c++ - 在构造函数的成员初始值设定项列表中使用带有指示符的初始值设定项列表来初始化匿名联合类型时编译错误
- javascript - 为什么 iframe 由于 URL 中的特殊字符而无法加载?
- kubernetes - 在 Kubernetes 中在确切日期(恰好一次运行)实现一次作业的最佳方法
- hidden-field - 如何通过 ontext 在 GraphDB 中成功上传饼图文件
- python - Selenium Python:即使在失败后也能执行代码
- python - 为什么为函数分配名称会自动执行该函数?
- python - 如何按小时四舍五入时间值?