From challman at gmail.com Tue Jul 10 12:15:32 2007 From: challman at gmail.com (Chris Hallman) Date: Tue, 10 Jul 2007 15:15:32 -0400 Subject: [paramiko] migrate from Telnet to SSH Message-ID: <9f68812f0707101215pea3a3ccka5565b0df67138d0@mail.gmail.com> I've written numerous programs that utilize Telnet to gather data, reload, or reconfigure network devices. I didn't use an interactive session like the demo SSH scripts use. I had the program issuing the commands. We're migrating from Telnet to SSH. I was hoping to find some examples where the program is interacting with the remote device but isn't using a shell. Does anyone have a program similar to what I described that I could look at? Thanks!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.lag.net/pipermail/paramiko/attachments/20070710/ae2fb9b6/attachment.htm From jbardin at bu.edu Wed Jul 11 07:00:42 2007 From: jbardin at bu.edu (James Bardin) Date: Wed, 11 Jul 2007 10:00:42 -0400 Subject: [paramiko] migrate from Telnet to SSH In-Reply-To: <9f68812f0707101215pea3a3ccka5565b0df67138d0@mail.gmail.com> References: <9f68812f0707101215pea3a3ccka5565b0df67138d0@mail.gmail.com> Message-ID: <4694E28A.6090608@bu.edu> Hi Chris, Take a look in the SSHClient class (download the most recent version though). You don't have to use an interactive shell. The SSHClient class also does nice things like handle an ssh-agent if available, and try to use your private keys if they're not encrypted. A *real* basic example: ############################ import paramiko client = paramiko.SSHClient() # ignore host keys for the test client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) client.connect('hostname', 22, 'username', 'Passw0rd') (stdin, stdout, stderr) = client.exec_command('command') print stdout.read() ############################ -jim Chris Hallman wrote: > I've written numerous programs that utilize Telnet to gather data, > reload, > or reconfigure network devices. I didn't use an interactive session > like the > demo SSH scripts use. I had the program issuing the commands. > > We're migrating from Telnet to SSH. I was hoping to find some examples > where > the program is interacting with the remote device but isn't using a > shell. > Does anyone have a program similar to what I described that I could > look at? > > > > Thanks!! > From jbardin at bu.edu Thu Jul 12 11:58:36 2007 From: jbardin at bu.edu (James Bardin) Date: Thu, 12 Jul 2007 14:58:36 -0400 Subject: [paramiko] migrate from Telnet to SSH In-Reply-To: <9f68812f0707121021n49e63072r37d15d9d5ec0fb6a@mail.gmail.com> References: <9f68812f0707101215pea3a3ccka5565b0df67138d0@mail.gmail.com> <4694E28A.6090608@bu.edu> <9f68812f0707120914o63a35f9elde91f746da929c7e@mail.gmail.com> <469659BB.5090506@bu.edu> <9f68812f0707120951t2d4c6b99iabdc8b39498148b4@mail.gmail.com> <9f68812f0707121021n49e63072r37d15d9d5ec0fb6a@mail.gmail.com> Message-ID: <469679DC.6020409@bu.edu> Chris Hallman wrote: > I found this: > > http://www.cpanforum.com/threads/851 > > I'd bet this is happening to me. Is there a way I can re-use the > channel or > open a dummy channel? > A channel is always closed after executing a command, and I *think* that's part of the protocol, so there may not be any way around it. I think what they mean by "dummy channel" is just opening a second channel, not using it, then closing it when your done. This may keep the server from closing the socket on you. You can see some examples of how to set up the channels directly in the demos, or in the SSHClient class itself. -jim From jbardin at bu.edu Thu Jul 12 09:41:31 2007 From: jbardin at bu.edu (James Bardin) Date: Thu, 12 Jul 2007 12:41:31 -0400 Subject: [paramiko] migrate from Telnet to SSH In-Reply-To: <9f68812f0707120914o63a35f9elde91f746da929c7e@mail.gmail.com> References: <9f68812f0707101215pea3a3ccka5565b0df67138d0@mail.gmail.com> <4694E28A.6090608@bu.edu> <9f68812f0707120914o63a35f9elde91f746da929c7e@mail.gmail.com> Message-ID: <469659BB.5090506@bu.edu> It seems the transport is being closed after the first command, probably by the server. This isn't the default behavior for openSSH, but it might be on cisco devices. I don't have anything cisco to connect to, so I can't offer much help on testing. I would step through a couple of the demos, and see where things might go wrong. You may need to start a new transport for each command if you don't want to use an interactive shell. The server may even be closing the socket, in which case you'll need to reconnect entirely. -jim Chris Hallman wrote: > Thanks! Ok, I was able to get a connection and retrieve the output of one > command, however when I try a second command, I receive an error: > > program: > > import paramiko > > client = paramiko.SSHClient() > > # ignore host keys for the test > client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) > > client.connect('rtr3926', 22, 'cworks', '#####') > > (stdin, stdout, stderr) = client.exec_command('sh ver | i IOS') > print stdout.read() > (stdin, stdout, stderr) = client.exec_command('sh ver | i IOS') > print stdout.read() > > output: > >> pythonw -u "sshclient.test.py" > > ******************************************************** > * * > * WARNING WARNING WARNING * > * * > * IF YOU ARE NOT AUTHORIZED TO CONNECT TO * > * THIS SYSTEM, YOU MUST DISCONNECT AT ONCE. * > * UNAUTHORIZED ACCESS MAY BE PROSECUTED. * > * * > ******************************************************** > Cisco IOS Software, 2800 Software (C2800NM-ADVSECURITYK9-M), Version > 12.4(8c), > RELEASE SOFTWARE (fc3) (output from first command) > > Traceback (most recent call last): > File "sshclient.test.py", line 12, in > (stdin, stdout, stderr) = client.exec_command('sh ver | i IOS') > File "c:\python25\Lib\site-packages\paramiko\client.py", line 315, in > exec_command > chan.exec_command(command) > AttributeError: 'NoneType' object has no attribute 'exec_command' >> Exit code: 1 > > What happened? I attached a copy one of my programs that currently uses > Telnet so that you can get an idea of what I need to do via SSH. > > > On 7/11/07, James Bardin wrote: >> >> Hi Chris, >> >> Take a look in the SSHClient class (download the most recent version >> though). You don't have to use an interactive shell. The SSHClient >> class also does nice things like handle an ssh-agent if available, and >> try to use your private keys if they're not encrypted. >> >> A *real* basic example: >> >> ############################ >> import paramiko >> >> client = paramiko.SSHClient() >> >> # ignore host keys for the test >> client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) >> >> client.connect('hostname', 22, 'username', 'Passw0rd') >> >> (stdin, stdout, stderr) = client.exec_command('command') >> print stdout.read() >> ############################ >> >> >> -jim >> >> >> Chris Hallman wrote: >> > I've written numerous programs that utilize Telnet to gather data, >> > reload, >> > or reconfigure network devices. I didn't use an interactive session >> > like the >> > demo SSH scripts use. I had the program issuing the commands. >> > >> > We're migrating from Telnet to SSH. I was hoping to find some examples >> > where >> > the program is interacting with the remote device but isn't using a >> > shell. >> > Does anyone have a program similar to what I described that I could >> > look at? >> > >> > >> > >> > Thanks!! >> > >> >> > > ------------------------------------------------------------------------ > > # > # This script obtains a directory listing, strips the extensions and telnets to the > # device (which is the filename in the directory). Then it writes the commands in the > # file to the device, saves config and writes it back to SYSMAN. It can be run using: > # python tftp.file.py > # > # Note: "os" is imported for future functionality. > # > # by: TCDH > # on: 10/17/05 > # release#2 > # revised: 10/18/05 TCDH - Added logic to check for offline devices and sign-on failures. > # 11/17/05 TCDH - Added logic to control the number of threads. > # 01/23/06 TCDH - Moved variables and main logic to the bottom of the program. > # 08/14/06 TCDH - Added tn.close() to properly close telnet sessions. > > import os, os.path, random, re, smtplib, socket, string, sys, telnetlib, threading, time > from time import strftime > from threading import Thread > > > class SendFile(threading.Thread): > def __init__(self, host): > """ This instantiates the class and tries to open a connection to the device, > with error checking. """ > Thread.__init__(self) > self.host = host > self.filename = filename > self.filepath = filepath > self.fileSize = fileSize > try: > self.tn = telnetlib.Telnet(self.host) > except socket.error, err: > if "Operation timed out" in err: > configResult[self.host] = ["connection timed out"] > return > elif "getaddrinfo failed" in err: > configResult[self.host] = ["DNS resolution failed"] > return > elif "No route to host" in err: > configResult[self.host] = ["device unreachable"] > return > elif "Network is unreachable" in err: > configResult[self.host] = ["device unreachable"] > return > else: > configResult[self.host] = ["unspecified network error"] > return > > def run(self): > """ This function is the main function. It calls the Logon function and the > TFTPfile function.""" > connect_status = self.Logon() > if connect_status == "authfail": > configResult[self.host] = ["authentication failed"] > self.tn.close() > return > transmit = self.TFTPFile() > self.tn.write("exit\n") > self.tn.close() > if transmit == "failed": > return > for x in range(6): > try: > os.remove(self.filepath) > except: > time.sleep(5) > continue > return > > def Logon(self): > """ This function attempts to logon to the device 3 times.""" > for x in range(3): > self.tn.read_until("Username:", 7) > self.tn.write(user + "\n") > (index, match, read) = self.tn.expect(["Password:"], 7) > self.tn.write(pswd + "\n") > (index, match, read) = self.tn.expect([self.host.upper()], 7) > if match: > return > if not match: > if x == 2: > return "authfail" > else: > continue > > def TFTPFile(self): > """ This functions does all the work. It does a write to make sure the > startup-confg and running-confg are similar and copies the file into running-confg > with error checking. If all is well, then it does a write to save the changes and > does a write net (with error checking).""" > self.tn.write("wr\n") > (index, match, read) = self.tn.expect(["OK"], 15) > if not match: > self.tn.write("yes\n") > time.sleep(random.uniform(0,2)) > self.tn.write("copy tf runn\n") > self.tn.read_until("host []?", 7) > time.sleep(random.uniform(0,2)) > self.tn.write("192.168.136.51\n") > self.tn.read_until("filename []?", 7) > time.sleep(random.uniform(0,2)) > self.tn.write(self.filename +"\n") > time.sleep(random.uniform(0,2)) > self.tn.read_until("[running-config]?", 7) > time.sleep(random.uniform(0,2)) > self.tn.write("\n") > time.sleep(random.uniform(0,2)) > x = self.tn.read_until(self.host.upper() + "#", 35) > if "% Incomplete command before pipe" in x: > configResult[self.host] = ["command authentication failed"] > return "failed" > elif "% Invalid input detected" in x: > configResult[self.host] = ["invalid command syntax"] > return "failed" > elif "^" in x: > configResult[self.host] = ["unexpected command error"] > return "failed" > else: > if "[OK" not in x: > configResult[self.host] = ["TFTP get failed"] > return "failed" > elif str(self.fileSize) not in x: > configResult[self.host] = ["TFTP filesize mismatch"] > return "failed" > else: > pass > self.tn.write("wr\n") > self.tn.read_until(self.host.upper() + "#", 7) > time.sleep(random.uniform(0,2)) > self.tn.write("wr net\n") > self.tn.read_until("]?") > time.sleep(random.uniform(0,2)) > self.tn.write("192.168.19.201\n") > self.tn.read_until("]?") > time.sleep(random.uniform(0,2)) > self.tn.write(self.host.lower() + "-confg\n") > self.tn.read_until("[confirm]") > time.sleep(random.uniform(0,2)) > self.tn.write("\n") > (index, match, read) = self.tn.expect(["OK"], 30) > if "Error opening tftp" in read: > configResult[self.host] = ["write net failed"] > return "failed" > > def count_active(): > """ This function returns the number of Getter threads that are alive """ > num_active = 0 > for thread in tlist: > if thread.isAlive(): > num_active += 1 > return num_active > > def emailResult(e, s, r, m): > """ This function send emails based on the input. """ > mailServer = smtplib.SMTP(e) > mailServer.sendmail(s, r, m) > mailServer.quit() > > configResult = {} > emailsrvr = "mail.publix.com" > threads = [] > dirPath = (r"c:\tftp") > dirList = os.listdir(dirPath) > Max_Threads = 20 > pswd = "#####" > receiver_list = [""] > sender = "" > subject = "TFTP file results" > text = "" > tlist = [] > user = "cworks" > logFile = (r"c:\logs\tftp.file.log") > output = file(logFile, "a") > output.write("\ntftp.file script started -" + strftime(" %H:%M:%S %x") + "\n") > output.flush() > > for entry in dirList: > host = entry.replace(".txt", "") > filename = entry.lower() > filepath = (dirPath + "\\" + filename) > fileSize = str(os.path.getsize(filepath)) + " bytes" > while count_active() >= Max_Threads: > time.sleep(1) > threads = SendFile(host) > tlist.append(threads) > threads.start() > > for thread in tlist: > thread.join() > > configResult_sorted = sorted(configResult.items()) > for x in range(len(configResult_sorted)): > text = text + str(configResult_sorted[x]) + "\n\r" > text = text.replace("[", "").replace("]", "").replace("'", "").replace("(", "").replace(")", "").replace(",", "\t") > output.write(text) > output.flush() > > for receiver in receiver_list: > header = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, receiver, subject) > heading = "If this email is blank, then no failures occurred.\r\n\r\n" > msg = header + heading + text > emailResult(emailsrvr, sender, receiver, msg) > > output.write("\ntftp.file script completed -" + strftime(" %H:%M:%S %x") + "\n") > output.flush() > output.close() > From jbardin at bu.edu Fri Jul 13 08:22:56 2007 From: jbardin at bu.edu (James Bardin) Date: Fri, 13 Jul 2007 11:22:56 -0400 Subject: [paramiko] migrate from Telnet to SSH In-Reply-To: <9f68812f0707130742m32c41ac2haaa04c4a9e7e0077@mail.gmail.com> References: <9f68812f0707101215pea3a3ccka5565b0df67138d0@mail.gmail.com> <4694E28A.6090608@bu.edu> <9f68812f0707120914o63a35f9elde91f746da929c7e@mail.gmail.com> <469659BB.5090506@bu.edu> <9f68812f0707120951t2d4c6b99iabdc8b39498148b4@mail.gmail.com> <9f68812f0707121021n49e63072r37d15d9d5ec0fb6a@mail.gmail.com> <469679DC.6020409@bu.edu> <9f68812f0707130742m32c41ac2haaa04c4a9e7e0077@mail.gmail.com> Message-ID: <469798D0.3030402@bu.edu> Chris Hallman wrote: > Is channel the same a TCP connection? > > I've looked around can't find any example similar to what I need nor > can I > figure out from the documentation what I need to do. I know that > client below > instantiates the object/class. It opens the TCP connection. I just don't > want to be creating thousands of TCP connections if I can get away with > re-using the existing one. I've no idea yet how to do what I need. If you > have any suggestions, I'd be grateful. > You're going to have to go beneath the SSHClient class, and use the building blocks yourself. The pydocs are very good if you haven't seen them - http://www.lag.net/paramiko/docs/ This is what I would try next. You can do this interactively in the python shell, idle, ipython, etc. ###### import socket import paramiko sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((''rtr3926', 22)) trans = paramiko.Transport(sock) trans.auth_password('user', 'password') # now open a channel that we're not going to use dummy_chan = trans.open_session() # here's the exec_command function from SSHClient def exec_command(command): chan = trans.open_session() chan.exec_command(command) stdin = chan.makefile('wb') stdout = chan.makefile('rb') stderr = chan.makefile_stderr('rb') return stdin, stdout, stderr stdin, stdout, stderr = exec_commnd('command') ########... Hopefully the dummy_chan being left open will prevent the server from trying to close the connection. -jim -- /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * James Bardin - Systems Analyst / Administrator I Boston University Department of Electrical and Computer Engineering 8 Saint Mary's St, Room 305, Boston, MA 02215 Ph:617-358-2785 http://www.bu.edu/ece/it * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ From jmatthews at Railpower.com Tue Jul 24 08:59:25 2007 From: jmatthews at Railpower.com (Matthews, James) Date: Tue, 24 Jul 2007 11:59:25 -0400 Subject: [paramiko] Paramiko connection does not react well to sync Message-ID: <067C9A1F6AFEB643895EA4513E116884B23A79@exfp1.Railpowertech.local> Greetings, I have been furiously testing a Python (v2.4.3) application built on wx.Python (v) that uses paramiko (v1.7) for an SSH connection to essentially a "bare-bones" Linux box running dropbear (v0.49). The setup was working great except for one annoying bug that kept popping up in different locations. Namely, it appears to happen in very random places during a very long process in which the application connects to the Linux box, moves a few files around, updates the image on the box, and then mounts two particular partitions to restore some files (namely for convenience so I don't have to do it manually after the image update). Now the problem appeared after somebody else went in and added some lines of code which they thought would make this process more reliable. I don't know if this is exactly what was causing the problem, but after weeks of debugging, tracing, and cursing I found what I believe the problem to be. Apparently, they had added a function to open a new session to execute a Linux command on the box, which just so happened to be the 'sync' command. They had put this in after every time I mounted a partition in order to access it, and their comments said something along the lines of, "#Make sure the File System is aware", or "#Give the File System time before accessing the file". It seems that around this command in the code, the 10 second connection check would sense a downed connection. I'm sorry for the length of this email, but basically my question is... Is it even necessary to perform a 'sync' operation after just a simple partition mount? And further more, would it make any sense for this to cause paramiko to close the Transport unexpectedly? James L. Matthews, III Computer Engineering Intern Railpower Hybrid Technologies 2021 Peninsula Dr. Erie, PA 16506 814-835-2212 ext. 236 Cell: 623-570-4509 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.lag.net/pipermail/paramiko/attachments/20070724/77b66e79/attachment.htm From battosaimykle at gmail.com Wed Jul 25 03:07:13 2007 From: battosaimykle at gmail.com (Mykle) Date: Wed, 25 Jul 2007 12:07:13 +0200 Subject: [paramiko] Problem with authentification Message-ID: <54e11fe0707250307m42b7c754m8988e695b0fbcf36@mail.gmail.com> Hi, I'm french so I apologize for mistakes I'm about to make with english... I installed Paramiko on a Debian Server for making connections with an SSH Server and here's my issue: I create a transport connection with the server for getting files from it. The server asks an authentification but the public key is kept by the SSH Server and recognize the computer by his public key username at computername, the server have a username for the public key. There's no password anyway ! Until now, I use a bash script which make an ssh connection with the Server (like 'ssh -x -a username at sshadress'), but I want to change that for some verification reasons. I mustn't have to put any key in the code... What I want is to connect to the Server and that this one accept this connection by only the recognization of the username at computername. The documentation doesn't really help me and I'm not pretty much good in Python (maybe that explains why I'm writing this mail...*sic*). Here's the begining of my code: import paramiko TR = paramiko.Transport((sshAdress,22)) ... ... Yeah I know, it's like there was nothing... Thank you for your help. Michael. -- Liv Ur Lif An B Liv...4Ever -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.lag.net/pipermail/paramiko/attachments/20070725/5df6ab3a/attachment.htm From challman at gmail.com Thu Jul 26 21:32:17 2007 From: challman at gmail.com (Chris Hallman) Date: Fri, 27 Jul 2007 00:32:17 -0400 Subject: [paramiko] no existing session Message-ID: <9f68812f0707262132u76af03abq2d42f6eae1fd217d@mail.gmail.com> I'm trying to write a program that connects to a Cisco router to run multiple commands and collect data. I've tried the following: import socket import paramiko sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((''rtr3926', 22)) trans = paramiko.Transport(sock) trans.auth_password('user', 'password') and I receive this error: >pythonw -u "paramiko.test.py" Traceback (most recent call last): File " paramiko.test.py", line 10, in trans.auth_password('####', '####') File "c:\python25\Lib\site-packages \paramiko\transport.py", line 1096, in auth_password raise SSHException('No existing session') paramiko.SSHException: No existing session >Exit code: 1 Any ideas why I'm receiving this error? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.lag.net/pipermail/paramiko/attachments/20070727/7f3a3afa/attachment.htm From toddw at activestate.com Fri Jul 27 09:40:54 2007 From: toddw at activestate.com (Todd Whiteman) Date: Fri, 27 Jul 2007 09:40:54 -0700 Subject: [paramiko] no existing session In-Reply-To: <9f68812f0707262132u76af03abq2d42f6eae1fd217d@mail.gmail.com> References: <9f68812f0707262132u76af03abq2d42f6eae1fd217d@mail.gmail.com> Message-ID: <46AA2016.3040704@activestate.com> Chris Hallman wrote: > > I'm trying to write a program that connects to a Cisco router to run > multiple commands and collect data. I've tried the following: > > import socket > import paramiko > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((''rtr3926', 22)) > > trans = paramiko.Transport(sock) > trans.auth_password('user', 'password') > > and I receive this error: > > >pythonw -u "paramiko.test.py " > Traceback (most recent call last): > File " paramiko.test.py ", line 10, in > trans.auth_password('####', '####') > File "c:\python25\Lib\site-packages > \paramiko\transport.py", line 1096, in auth_password > raise SSHException('No existing session') > paramiko.SSHException: No existing session > >Exit code: 1 > > Any ideas why I'm receiving this error? > > Hi Chris, You need to start the client session, i.e. trans = paramiko.Transport(sock) trans.start_client() # negotiate with the server trans.auth_password('user', 'password') Check out the demos that are included in the paramiko source for more examples. Cheers, Todd