torchnw |
10-02-2012 01:23 PM |
Python+paramiko - Can't create SSH connection when running as root
Hi,
I'm trying to create a python script to automate backup of networking device configurations over SSH. Using paramiko I can create the connection when running as a normal user ( which I added to group "root" to facilitate storing the output files under /var/log ), but when run as root, it fails to authenticate. The target device is a Cisco switch. These are the relevant bits of code:
Code:
class Connection(object):
def __init__(self, target, username, password):
self.target = target
self.username = username
self.password = password
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# I've tried all of the following, but same result
self.ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
#self.ssh.load_host_keys("/root/.ssh/known_hosts")
#self.ssh.load_system_host_keys()
class Cisco_IOS(Connection):
def fetch(self):
self.ssh.connect(self.target, username=self.username, password=self.password, )
channel = self.ssh.invoke_shell()
channel.send('en\n')
time.sleep(2)
channel.send(self.password+"\n")
time.sleep(2)
flush = channel.recv(3000)
print flush
catch_error = re.compile("[Ee]rror")
if catch_error.search(flush):
log("Error authenticating to " + self.target +". Enable password different from login password")
channel.send("terminal length 0\n")
channel.send("show run\n")
time.sleep(5)
config = channel.recv(20000)
print config
return config
Now I believe it's somehow related to the user's and root's "~/.ssh/known_hosts" files, but I'm not sure how. The public keys are in both files, and also the line
Code:
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
should take care of adding the keys if they were missing. Permissions on both files are the same (644).
The error I'm getting is:
Quote:
File "./paratest.py", line 35, in fetch
self.ssh.connect(self.target, username=self.username, password=self.password, )
File "/usr/lib/python2.4/site-packages/paramiko/client.py", line 327, in connect
self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
File "/usr/lib/python2.4/site-packages/paramiko/client.py", line 481, in _auth
raise saved_exception
paramiko.AuthenticationException: Authentication failed.
|
As mentioned, I don't get this while running as a normal user, only as root. Any suggestions would be appreciated.
|