Paramiko and sudo
I've been searching the nets for some time now for a solution to my problem, and no luck.
My issue is that I can't seem to get sudo commands to run with paramiko.
At first, I tried to simply use the SSHClient().exec_command(command) function to execute a sudo command, but this errors:
sudo: sorry, you must have a tty to run sudo
Then, following the advice of this post: How to make a sudo command using Paramiko, I tried this:
#self._ssh is the SS开发者_运维百科HClient object
self._ssh.invoke_shell().exec_command(command)
However, most of the time, this just gives me:
File "pipelines/load_instance/ssh_tools.py", line 71, in executeCommand
stdin, stdout, stderr = self._ssh.invoke_shell().exec_command(command)
File "<absolute_path>/paramiko/channel.py", line 213, in exec_command
self._wait_for_event()
File "<absolute_path>/paramiko/channel.py", line 1084, in _wait_for_event
raise e
paramiko.SSHException: Channel closed.
The other, I'd have to say, 40% of the time, I get this:
File "<absolute_path>/paramiko/client.py", line 291, in connect
sock.connect(addr)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
As a side note, I'm attempting to run these sudo commands on an Amazon Web Services EC2 instance, so I'm confused as to why I would get the Connection Refused error, since each time I run this code it's on a fresh new instance...
Also, I'm using paramiko 1.7.6.
This is a common problem on recent distributions and impacts more than just paramiko. (I ran into it the other day when I upgraded a box from fedora2 to latest. Several ssh/sudo management scripts broke)
As long as you have access to the remote host, you can edit /etc/sudoers
and comment out the line: Defaults requiretty
Details in the sudoers man page:
requiretty
If set, sudo will only run when the user is logged in to a real tty. This will disallow things like "rsh somehost sudo ls" since rsh(1) does not allocate a tty. Because it is not possible to turn off echo when there is no tty present, some sites may with to set this flag to prevent a user from entering a visible password. This flag is off by default.
stdin, stdout, stderr = client.exec_command(cmd, get_pty=True)
精彩评论