Paramiko SSH - Multiple Authentication Credentials with Python - python-2.7

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!!!!

Related

How to send escape sequences over ssh connection in Paramiko for example ESC+E.Can someone send a link to a list

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

Pymongo on raspberry pi 3 wait too much to raise an error

I have an issue with pymongo on raspberry pi 3. The thing is when I run the script normally (I mean, I have internet connection and database connection, so there is not problem writing on database) I disconnect the wi-fi or ethernet from the Raspberry in order to get an error and handle it later but, when I disconnect the internet the script stops in the "insert_one" command of pymongo, like waiting until it gets internet connection again... so... the error raised several minutes later, like 25 minutes and that is not good for me, because I need to get the error inmediatly, so I can do some savings on a csv file.
from pymongo import MongoClient
from pymongo import errors
from pymongo import client_options
from pymongo import settings
url = 'emaweather.hopto.org'
port = 27017
client_options.ClientOptions.server_selection_timeout = 1
try:
client = MongoClient(url, port)
db = client['weather-mongo']
print('Cliente: ' ,client)
print('DB: ', db)
except errors.ConnectionFailure as e:
print('Error: ', e)
def main():
while True:
try:
__readCSV()
utc_now = pytz.utc.localize(datetime.datetime.utcnow())
pst_now = utc_now.astimezone(pytz.timezone("America/Asuncion"))
dateNowIsoFormat = pst_now.isoformat()
print (dateNowIsoFormat)
temperature,pressure,humidity = readBME280All()
dbDataTemp = temperature
print (dbDataTemp)
dbDataHum = round(humidity,2)
print (dbDataHum)
dbDataPress = round(pressure,2)
print (dbDataPress)
dbData = {"date": dateNowIsoFormat, "temp": dbDataTemp, "hum": dbDataHum, "press": dbDataPress}
db.data.insert_one(dbData)
print('Writed on MongoDB')
time.sleep(5)
except errors.PyMongoError as error:
print (error)
if __name__=="__main__":
main()

Paramiko hanging when encounters missing output

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)

why is Exact Target FUEL SDK not validating my API keys?

I am working with the FUEL SDK for Exact Target API. I have setup my enviorment variables but the app keeps denying me data, and throws the following error message
raise Exception('Unable to validate App Keys(ClientID/ClientSecret) provided: ' + repr(r.json()))
Exception: Unable to validate App Keys(ClientID/ClientSecret) provided: {u'errorcode': 1, u'message': u'Unauthorized', u'documentation': u''}
I am looking in the client, but do not see why the authentication would be stopping. here is my code:
import os
os.environ["FUELSDK_CLIENT_ID"] = ""
os.environ["FUELSDK_CLIENT_SECRET"] = ""
os.environ["FUELSDK_DEFAULT_WSDL"] = "https://webservice.exacttarget.com/etframework.wsdl"
os.environ
["FUELSDK_AUTH_URL"] = "https://auth.exacttargetapis.com/v1/requestToken?legacy=1"
#os.environ["FUELSDK_WSDL_FILE_LOCAL_LOC"] = "C:\Users\Aditya.Sharma\AppData\Local\Temp\ExactTargetWSDL.s6.xml"
# Add a require statement to reference the Fuel SDK's functionality:
import FuelSDK
# Next, create an instance of the ET_Client class:
myClient = FuelSDK.ET_Client()
# Create an instance of the object type we want to work with:
list = FuelSDK.ET_List()
# Associate the ET_Client to the object using the auth_stub property:
list.auth_stub = myClient
# Utilize one of the ET_List methods:
response = list.get()
# Print out the results for viewing
print 'Post Status: ' + str(response.status)
print 'Code: ' + str(response.code)
print 'Message: ' + str(response.message)
print 'Result Count: ' + str(len(response.results))
print 'Results: ' + str(response.results)
Could someone please tell me why I am being shut out?
here is git repository I am using: https://github.com/salesforce-marketingcloud/FuelSDK-Python
Thank you in advance.
Update Client KEY/PWD in client.py

how to run two process in parallel using multiprocessing module in python

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