Paramiko Script is hanging, attempting to ssh through a list of IP address and execute a few commands to extract information that may or may not be there. For example if i was to implement a uname -a it should reveal the hostname, however if the next server in the list doesn't have a hostname then it seems the script is hanging.
import paramiko
import sys
import io
import getpass
import os
import time
# ***** Open Plain Text
f = open("file.txt")
# ***** Read & Store into Variable
hn=(f.read().splitlines())
f.close()
# ***** Credentials
username = raw_input("Please Enter Username: ")
password = getpass.getpass("Please Enter Passwod: ")
# ***** SSH
client=paramiko.SSHClient()
def connect_ssh(hn):
try:
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hn, 22, username, password, look_for_keys=False, allow_agent=False)
print 'Connection Attempting to: '+(hn)
channel = client.get_transport().open_session()
channel.invoke_shell()
#print "CMD
#channel.send("CMD"+"\n")
channel.send("command"+"\n")
CMD = (channel.recv(650000))
print (CMD)
except Exception, e:
print '*** Caught exception: %s: %s' % (e.__class__, e)
try:
channel.close()
except:
pass
# *****Create Loop through input.txt
for x in hn:
connect_ssh(x)
Related
I am trying to send ESC+E and other combinations with ESC key over ssh using Paramiko in Python but unable to find a list which can guide.
Can someone please help
import paramiko
import time
import os
import sys
time.sleep(1)
ip = "x"
host = ip
username = "aaa"
password = "ffffffffff"
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,username=username,password=password,port=5022)
channel=ssh.invoke_shell()
time.sleep(2)
channel.send("W2KTT\n")
time.sleep(5)
output=channel.recv(9999)
print output
channel.send("display alarms \n")
time.sleep(5)
output=channel.recv(9999)
print output
time.sleep(1)
channel.send("\t \t \t n \x1B3 ") #need to send ESC+E key combination here
would appreciate your advice how to exclude hosts from scanning inside the nm.scan().I have the following script which works perfectly when i enter the range : for example 10.0.0.0/24
import sys
import os
import subprocess
import csv
import nmap # import nmap.py module
try:
nm = nmap.PortScanner() # instantiate nmap.PortScanner object
except nmap.PortScannerError:
print('Nmap not found', sys.exc_info()[0])
sys.exit(0)
except:
print("Unexpected error:", sys.exc_info()[0])
sys.exit(0)
file = raw_input('\nEnter the name of the file where the scan will be saved/add .csv/: ')
ip_range = raw_input('\nEnter the IP range you want to scan/in the following foramt:x.x.x.x/mask: ')
nmap_arguments= raw_input('\nEnter the nmap arguments : ')
nm.scan(hosts=ip_range, arguments= nmap_arguments)
nm.command_line() # get command line used for the scan
nm.scaninfo() # get nmap scan informations {'tcp': {'services': '22-443', 'method'nect'}}
nm.all_hosts() # get all hosts that were scanned
if (len(sys.argv) > 1 and sys.argv[1]):
save_csv_data(nm.csv(), path=sys.argv[1])
else:
save_csv_data(nm.csv())
print "Completed!"
but For example if i want to scan the range but exclude 2 hosts , when i enter :nm.scan(hosts='10.0.0.0/24 --exclude 10.0.0.1, 10.0.0.2, arguments= nmap_arguments) - it excludes only 10.0.0.1 but still scanning 10.0.0.2.So bottom line is how to enter the IP part inside the nmap()
I got it.Needed to put the arguments first:
nm.scan(arguments='-sT --open --exclude X.X.X.X,X.X.X.X',hosts='X.X.X.0/24')
My requirement is to capture logs for a particular http request sent to server from project server log file. So have written two function and trying to execute them parallel using multiprocessing module. But only one is getting executed. not sure what is going wrong.
My two functions - run_remote_command - using paramiko module for executing the tail command on remote server(linux box) and redirecting the output to a file. And send_request - using request module to make POST request from local system (windows laptop) to the server.
Code:
import multiprocessing as mp
import paramiko
import datetime
import requests
def run_remote_command():
basename = "sampletrace"
suffixname = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
filename = "_".join([basename, suffixname])
print filename
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname='x.x.x.x',username='xxxx',password='xxxx')
except Exception as e:
print "SSH Connecting to Host failed"
print e
ssh.close()
print ssh
tail = "tail -1cf /var/opt/logs/myprojectlogFile.txt >"
cmdStr = tail + " " + filename
result = ''
try:
stdin, stdout, stderr = ssh.exec_command(cmdStr)
print "error:" +str( stderr.readlines())
print stdout
#logger.info("return output : response=%s" %(self.resp_result))
except Exception as e:
print 'Run remote command failed cmd'
print e
ssh.close()
def send_request():
request_session = requests.Session()
headers = {"Content-Type": "application/x-www-form-urlencoded"}
data = "some data "
URL = "http://X.X.X.X:xxxx/request"
request_session.headers.update(headers)
resp = request_session.post(URL, data=data)
print resp.status_code
print resp.request.headers
print resp.text
def runInParallel(*fns):
proc = []
for fn in fns:
p = mp.Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()
if __name__ == '__main__':
runInParallel(run_remote_command, send_request)
Output: only the function send_request is getting executed. Even I check the process list of the server there is no tail process is getting created
200
Edited the code per the #Ilja comment
I have the following code:
import paramiko
import time
import re
import sys
import random
import fileinput
ip_address = raw_input("Enter a valid WAP IP: ")
#Open SSHv2 connection to devices
def open_ssh_conn(ip):
try:
#Logging into device
session = paramiko.SSHClient()
#AutoAddPolicy
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#Passing the necessary
session.connect(ip, username = 'myUsername', password = 'myPassword')
#Start an interactive shell session on the switch
connection = session.invoke_shell()
#Commands
connection.send("enable\n")
time.sleep(1)
connection.send("show version\n")
time.sleep(1)
#Checking command output for IOS syntax errors
output = connection.recv(65535)
#Checking command output for IOS Syntax errors
if re.search(r"% Invalid input detected at", output):
print "* There was at least one IOS syntax error on device %s" % ip
else:
print "\nDONE for device %s" % ip
#Test for reading command output
print output + "\n"
#Closing the connection
session.close()
except paramiko.AuthenticationException:
print "* Invalid username or password. \n* Please check
the username/password file or the device configuration!"
print "* Closing program...\n"
#Calling the SSH function
open_ssh_conn(ip_address)
How can I test multiple credential without getting kick out of the program when an exception is caught?
for example, try this new credentials:
session.connect(ip, username = 'myNewUsername', password = 'myNewPassword')
I figured it out! I created a nested list with the credentials:
list = [['username1', 'password1'], ['username2', 'password2'], \
['username3', 'password3']]
Then, created a for loop and put my code inside:
for elem in list:
my code...
# this is the connect line:
session.connect(ip, username = elem[0], password = elem[1])
That did it!!!!
I am trying to run a python script from bash script to upload files to a website using crontab. The script runs from terminal but doesn't work from crontab and the error is
"Error: <urlopen error [Errno -2] Name or service not known>"
The python script is:
#!/usr/bin/env python
from ConfigParser import ConfigParser
from mechanize import Browser, RobustFactory
import base64
from os.path import basename
import sys
import os
print(os.environ)
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Error: 1 argument needed"
sys.exit(1)
#DATA FROM CFG FILE
url = "http:website"
cfn = "absolute_path/upload.cfg"
cfg = ConfigParser()
try:
cfg.read(cfn)
usr = cfg.get('Auth', 'user')
pwd = cfg.get('Auth', 'pass')
except Exception, e:
print "Error:", e
sys.exit(1)
if not usr or not pwd:
print "Error: username or password not valid."
sys.exit(1)
filename = sys.argv[1]
try:
br = Browser(factory=RobustFactory())
br.addheaders.append(('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (usr, pwd))))
br.open(url)
br.select_form(nr=1)
br.form.add_file(open(filename, 'rb'), 'text/plain', basename(filename))
br.submit()
print "File '%s' successfully uploaded" % filename
sys.exit(0)
except Exception, e:
print "Error:", e
sys.exit(1)
When I try to "print(os.environ)" in python script in the case of manual run and using crontab:
with crontab :
"{'MAILTO': '/var/mail/envclim', 'LANG': 'en_US.UTF-8', 'SHELL': '/bin/sh', 'XDG_RUNTIME_DIR': '/run/user/1000', 'SHLVL': '2', 'PYTHONPATH': '/usr/lib/python2.7/site-packages:/usr/lib/python2.7/site-packages/', 'OLDPWD': '/home/envclim/upload_sdswas', 'PWD': '/home/envclim/upload_sdswas/upload_scripts', 'LOGNAME': 'envclim', 'USER': 'envclim', 'HOME': '/home/envclim', 'PATH': '/bin:/usr/bin:/usr/local/bin:/usr/local/CDO/bin', 'XDG_SESSION_ID': '6', '_': '/usr/bin/python'}"
but in the manual case , there is the proxy, as the following:
{'HTTP_PROXY': 'http://10.51.51.51:80/', 'KDE_IS_PRELINKED': '1', 'ALL_PROXY': 'socks://10.51.51.51:80/', 'NO_PROXY': 'localhost,127.0.0.0/8,::1', 'GJS_DEBUG_OUTPUT': 'stderr', 'http_proxy': 'http://10.51.51.51:80/', 'FTP_PROXY': 'http://10.51.51.51:80/',----------}
In crontab, I add :
SHELL=/bin/sh
PATH=/bin:/usr/bin
PYTHONPATH=/usr/lib/python2.7/site-packages
MAILTO=/var/mail/envclim
I am using fedora19. I tried to disabled proxy, but the script didn't work at all.
please, can anyone solve this problem?
Thanks in advance
Zeinab
Thanks alot for your comments, I solved this problem by adding these lines in crontab:
PYTHONPATH=/usr/lib/python2.7/site-packages
HTTP_PROXY=http://10.51.51.51:80/
and in the bash file that used to run the python script:
export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/site-packages/
export LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib:/usr/local/usr/lib