counsel to the library to work with SSH. The main requirement is normal operation with the utility sudo. I have already tried and what I am suffering:
- paramiko - can not sudo at all, trying after a call to serve in STDIN password, but sudo wrote that then type: "No ttys present"
- pxssh - mmmmmm, very slow, very very slow, awkward
- fabric - can sudo only in what is an ideal world, as there is to work with different users and where i need send password ?
Have normal libraries that work with sudo, or no开发者_运维问答t?
Rather than force sudo
to work without a tty, why not get Paramiko to allocate you a TTY?
Paramiko and Pseudo-tty Allocation
I think you are looking for fabric.
You can configure sudo to work without a real terminal with 'requiretty' setting. From sudoers manual:
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 site may wish to set this flag to prevent a user from entering a visible password. This flag is off by default.
This works for me with paramiko. Depending o what are you doing, you can also look at something like pexpect.
I had the same problem with pxssh at first: it was extremely slow!
Here is a way I found to make it run quicker:
#!/usr/bin/python
import pxssh
import getpass
try:
s = pxssh.pxssh()
s.PROMPT = "#"
hostname = raw_input('hostname: ')
username = raw_input('username: ')
password = getpass.getpass('password: ')
s.login(hostname, username, password, auto_prompt_reset=False)
s.sendline('ls') # run a command
s.prompt() # match the prompt
print(s.before) # print everything before the prompt.
s.sendline('ls -l /tmp') # run a command
s.prompt() # match the prompt
print(s.before) # print everything before the prompt.
s.logout()
except pxssh.ExceptionPxssh as e:
print("pxssh failed on login.")
print(e)
The key part is s.PROMPT = "#"
and auto_prompt_reset=False
in s.login()
.
This method requires that you know the pattern for the prompt (in my case it is "#", I think the PROMPT attribute can be set to a regular expression).
I also had some problems with login speed on pxssh. I tried using the code referenced above, but still was seeing 10+ seconds just to login. Using the original_prompt argument fixed the issue for me. You need to make sure to set the original_prompt to what you see when you first ssh into the machine, which in my case ended in '>'.
#!/usr/bin/env python
from pexpect import pxssh
host = 'hostname.domain'
user = 'username'
password = 'password'
terminal = pxssh.pxssh()
terminal.login(host, user, original_prompt='[>$]')
精彩评论