Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在需要Sudo和密码输入的远程服务器上执行命令-Paramiko_Python_Ssh_Sudo_Paramiko - Fatal编程技术网

Python 在需要Sudo和密码输入的远程服务器上执行命令-Paramiko

Python 在需要Sudo和密码输入的远程服务器上执行命令-Paramiko,python,ssh,sudo,paramiko,Python,Ssh,Sudo,Paramiko,我正在尝试使用PythonParamiko(linux2上的Python2.7.9)在远程机器上执行sudo命令 下面是代码。当我执行代码时,它每次都会给出不同的输出,而当我在python>>>cmdline中运行相同的代码时,它工作正常 import paramiko import sys import time def send_string_and_wait(command, wait_time, should_print): shell.send(command) time.

我正在尝试使用PythonParamiko(linux2上的Python2.7.9)在远程机器上执行sudo命令 下面是代码。当我执行代码时,它每次都会给出不同的输出,而当我在python>>>cmdline中运行相同的代码时,它工作正常

import paramiko
import sys
import time
def send_string_and_wait(command, wait_time, should_print):
   shell.send(command)
   time.sleep(wait_time)
   receive_buffer = shell.recv(1024)
   if should_print:
     return  receive_buffer

dbname='test'
cl='testdb'
host='testhost'
owner='uname'
passwd='p'


client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(str(host), username=str(owner),  password=str(passwd), port=22)
shell = client.invoke_shell()
send_string_and_wait("sudo su - oracle\n", 1, True)
send_string_and_wait(str(passwd) + "\n", 1, True)
a=send_string_and_wait("sh Validation_Final.sh" + str(' ') +  str(dbname) + str(' ') + str(cl) + "\n", 0, True)
print a
client.close() 


如有任何建议,我们将不胜感激,谢谢

几年前我也遇到过类似的问题,结果可能有一些原因

一种可能的选择是,调用等待获取shell提示符以返回。但是,对于需要
sudo
的命令,行为可能会改变:在某些情况下,它将要求您首先输入密码。在其他情况下(例如,如果您刚刚使用了
sudo
,但尚未超时),则不再需要密码。这种不一致性可能会导致问题

看看-使用
-k
可能会解决您的问题

为了解决这个问题,您必须定义(如果可能的话)
sudo
始终需要密码,从而使其一致


另一个可能引起的问题是shell提示符的定义(一些shell使用
,其他shell使用
$
);对于
sudo
,情况可能也是如此-它可能打印
密码:
,其中不包含shell提示,远程命令代理可能无法识别,并且可能打印其他内容,例如
密码

谢谢你的回复,我试过sudo-k,但是运气不好。有趣的是,当我硬编码dbname和客户机值时,比如[“send_string_和_wait('sh/orashare/ettool/Validation_Final.sh dbname client'+“\n”,1,True)””),它是有效的,但当传递变量“send_string_和_wait”(“sh/orashare/ettool/Validation_Final.sh”+“+str(dbname)+”+“+str(cl)+“\n”,0,True)”时,我面临这个问题“我想这一定是语法问题,如果我错了,请纠正我。试着看看你从远程服务器得到了什么。使用
-k
只能确保远程服务器以一致的方式运行。但是,您必须记住,当请求密码时,它不使用shell符号(如
$
),因此如果paramiko只等待其中一个,它将阻塞。您必须将其配置为引用
密码:
(或系统中出现的任何密码)被视为该调用的shell符号。最后,我将wait_time参数更改为5秒,即[a=send_string_和_wait(“sh Validation_Final.sh”+str(“”)+str str(dbname)+str str str(“”)+str str(cl)+“\n”,5,True)执行代码需要3到4秒