diff --git a/tsshbatch.py b/tsshbatch.py index 00b8dfe..c68f39b 100755 --- a/tsshbatch.py +++ b/tsshbatch.py @@ -20,7 +20,7 @@ CMDINCL = PROGENV + "CMDS" HOSTINCL = PROGENV + "HOSTS" -CVSID = "$Id: tsshbatch.py,v 1.220 2016/01/16 17:06:51 tundra Exp $" +CVSID = "$Id: tsshbatch.py,v 1.221 2016/01/16 19:47:18 tundra Exp $" VERSION = CVSID.split()[2] CPRT = "(c)" PROGDATE = "2011-2016" @@ -247,6 +247,24 @@ # End of 'ConditionLine()' +##### +# Setup An SSH Connect +##### + +def ConnectSSH(host, user, pw, time): + + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + + if KEYEXCHANGE: + ssh.connect(host, username=user, timeout=time) + else: + ssh.connect(host, username=user, password=pw, allow_agent=False, look_for_keys=False, timeout=time) + + return ssh + +# End of 'ConnectSSH()' + ##### # Check To See If A Key Exists In A String, Excluding Quoted Substrings @@ -347,18 +365,9 @@ def HostFileTransfer(host, user, pw, filelist, GET=False): + # Get an sftp connection and move files try: - ssh = paramiko.SSHClient() - - # Connect and run the command, reporting results as we go - - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - - if KEYEXCHANGE: - ssh.connect(host, username=user, timeout=TIMEOUT) - else: - ssh.connect(host, username=user, password=pw, allow_agent=False, look_for_keys=False, timeout=TIMEOUT) - + ssh = ConnectSSH(host, user, pw, TIMEOUT) sftp = ssh.open_sftp() for src in filelist: @@ -437,19 +446,9 @@ if NOISELEVEL == SILENT: Format = False - ssh = paramiko.SSHClient() - # Connect and run the command, reporting results as we go - try: - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - - if KEYEXCHANGE: - ssh.connect(host, username=user, timeout=TIMEOUT) - - else: - ssh.connect(host, username=user, password=pw, allow_agent=False, look_for_keys=False, timeout=TIMEOUT) - + ssh = ConnectSSH(host, user, pw, TIMEOUT) if NOISELEVEL != QUIET: PrintReport([host, CONSUCCESS], FORMAT=Format) @@ -526,7 +525,11 @@ except: PrintReport([host, eCMDFAILURE % (eNOCONNECT % str(sys.exc_info()[1]))], HANDLER=PrintStderr) - ssh.close() + # Close any remaining ssh connection + try: + ssh.close() + except: + pass # End of 'HostCommands()'