I am trying to grab the serial number from a Banner. I have successfully done it by storing the banner content in a file, but now I would like to try without storing it in a file. Below is the snippet of code:
import argparse
import logging
import paramiko
def grab_banner(ip_address, port):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(ip_address, port=port, username='username', password='bad-password-on-purpose')
except:
return client._transport.get_banner()
def GetSerialNo(ip_address,Banner):
fp1=open("Baner","w")
fp1.write(Banner)
fp1.close()
fp2=open("Baner","r")
for line in fp2:
if re.search("System S/N", line):
Serial = line.split()
return Serial[2]
fp2.close()
if __name__ == '__main__':
logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description='This is a demo script')
parser.add_argument('-s','--ipsetups', help='IP Address')
args = parser.parse_args()
Setup_File=args.ipsetups
fp=open(Setup_File,"r")
for line in fp.readlines():
IP = line.strip()
logger.info("================================ WORKING on %s ===================================",IP)
Banner = grab_banner(IP, 22)
serial = GetSerialNo(IP, Banner)
logger.info("Serial Number is -> %s",serial)
fp.close()
The above code is working fine, but now I am trying to do it by storing it in some variable and then grabbing the serial number. But I'm unable to do so. Below is what I am trying to do:
def get_ip(Setup_File):
IPS = []
with open(Setup_File, 'r') as f:
for line in f:
IPS = line.split()
return IPS
def grab_banner(ip_address, port):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(ip_address, port=port, username='username', password='bad-password-on-purpose')
except:
return client._transport.get_banner()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='This is a demo script by Mangesh Pardhi.')
parser.add_argument('-s','--ipsetups', help='PD-Setup IP Address')
args = parser.parse_args()
Setup_File=args.ipsetups
print Setup_File
IPS = get_ip(Setup_File)
for IP in IPS:
logger.info("================================ WORKING on %s ===================================",IP)
Banner = grab_banner(IP, 22)
if "System S/N" in Banner:
XXXXXXXXXXHow To procees XXXXXXXXXXx
serial = Serial[2]
logger.info("Serial Number is -> %s",serial)
You could just simplify GetSerialNo in your original code.
def GetSerialNo(ip_address, Banner):
for line in Banner.split('\n'):
if re.search("System S/N", line):
Serial = line.split()
return Serial[2]
(Surely you already know that you don't need the parameter ip_address there.)
Related
in the following and executable code you see a SessionScope()-class. In the main()-function the user can log on to his MySQL database server. We take a look in the class. There are two magic methods (__enter__, __exit__),
that allows me to use the object easily with the with-statement. In this statement you also see the program uses session. When the __exit__()-method is
calling then the session is closed. BUT we know that will give the connection back to the connection pool of Engine. That means, its doesn't close the connection directly,
because the connection is pooling. So far so good. On GUI side the user has the option to log off. Well, let us imagine: After a very very very long work with the
database the user wants the connection to be actually closed, but he doesn't wants the program closes itself. Later perhaps the user will log on again and continue working. Until then the program is still running without connection to
the database. The user doesn't need the connection anymore.
That means for python, we don't need the SessionScope()-class anymore. In my case we can remove/clean up this class with del session_scope My idea is to re-implement the __del__()-method. In this method I want to
close all connections of the connection pool. If this class is cleared/removed all connections should be disconnected, that is the reason why I use the del in log_out()-function.
Is this the right way to do this?
TA, your Sophus
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
class SessionScope(object):
def __init__(self, dbms, dbdriver, dbuser, dbuser_pwd, db_server_host, dbport, db_name):
self.dbms = dbms
self.dbdriver = dbdriver
self.dbuser = dbuser
self.dbuser_pwd = dbuser_pwd
self.db_server_host = db_server_host
self.dbport = dbport
self.db_name = db_name
url = '{}+{}://{}:{}#{}:{}/{}'.format(
self.dbms, self.dbdriver, self.dbuser, self.dbuser_pwd, self.db_server_host, self.dbport, self.db_name)
self.engine = create_engine(url, encoding='utf8', echo=True)
# store a sessionmaker for this db connection object
self._Session = sessionmaker(bind=self.engine)
self.session = None
def __enter__(self):
self.session = self._Session()
return self._Session()
def __exit__(self, exception, exc_value, traceback):
try:
if exception:
self.session.rollback()
else:
self.session.commit()
finally:
self.session.close()
self.session = None
def __del__(self):
self.engine.dispose()
def log_out(session_scope):
del session_scope
def main():
dbm_system = raw_input("Which DBMS? (type for e.g. mysql): ")
dbm_driver = raw_input("Which db-driver? (type for e.g. pymysql): ")
db_host = raw_input("Server-Host: ")
db_user = raw_input("Database-user: ")
db_passwd = raw_input("User-Password: ")
db_name = raw_input("Database Name: ")
db_port = raw_input("Port: ")
try:
session_scope = SessionScope(dbm_system, dbm_driver, db_user, \
db_passwd, db_host, db_port, db_name)
with session_scope as session:
# Its just for testing.
print session.execute("SELECT VERSION();")
log_out(session_scope)
except SQLAlchemyError as err:
print "ERROR", err[0]
if __name__ == '__main__':
main()
EDIT #1:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
class SessionScope(object):
def __init__(self, engine):
self.engine = engine
# store a sessionmaker for this db connection object
self._Session = sessionmaker(bind=self.engine)
self.session = None
def __enter__(self):
self.session = self._Session()
return self._Session()
def __exit__(self, exception, exc_value, traceback):
try:
if exception:
self.session.rollback()
else:
self.session.commit()
finally:
self.session.close()
self.session = None
class Engine(object):
def __init__(self, dbms, dbdriver, dbuser, dbuser_pwd, db_server_host, dbport, db_name):
self.dbms = dbms
self.dbdriver = dbdriver
self.dbuser = dbuser
self.dbuser_pwd = dbuser_pwd
self.db_server_host = db_server_host
self.dbport = dbport
self.db_name = db_name
url = '{}+{}://{}:{}#{}:{}/{}'.format(
self.dbms, self.dbdriver, self.dbuser, self.dbuser_pwd, self.db_server_host, self.dbport, self.db_name)
self._Engine = create_engine(url, encoding='utf8', echo=True)
def __enter__(self):
return self._Engine
def __exit__(self, exception, exc_value, traceback):
'''
Make sure the dbconnection gets closed
'''
self._Engine.dispose()
logged_in = True
def main():
dbm_system = raw_input("Which DBMS? (type for e.g. mysql): ")
dbm_driver = raw_input("Which db-driver? (type for e.g. pymysql): ")
db_host = raw_input("Server-Host: ")
db_user = raw_input("Database-user: ")
db_passwd = raw_input("User-Password: ")
db_name = raw_input("Database Name: ")
db_port = raw_input("Port: ")
try:
with Engine(dbm_system, dbm_driver, db_user, \
db_passwd, db_host, db_port, db_name) as engine:
while logged_in:
with SessionScope(engine) as session:
# Its just for testing.
print session.execute("SELECT VERSION();")
except SQLAlchemyError as err:
print "ERROR", err[0]
if __name__ == '__main__':
main()
The __del__ method doesn't work like that. It's not called when a user does del some_instance, but when the interpreter's garbage collector sees that there are no live references to the object. Your log_out method does nothing, since the reference it is deleting is an extra one that's created to pass the session to it as an argument (the outside reference still remains).
I suspect you really want to have two different classes that both support the context manager protocol. This lets you have two nested with statements, one which last through an entire login and that only lasts for the length of one per database session. Something like this:
with Engine() as engine:
while logged_in:
with Session(engine) as session:
do_stuff()
You may want another loop around the outer with so that the program doesn't exit after you log out.
I have login page where the user inputs the username and password. I have made the username as session variable in the /login view function and would like to use this variable outside the view function in the main body of the code in a if-else block.
session['username'] = request.form['username'].lower()
How do I do this?
Here is part of the code for this:
import os
import csv
import pymysql
import pymysql.cursors
from datetime import date
import calendar
import ssl
from ldap3 import Connection, Server, ANONYMOUS, SIMPLE, SYNC, ASYNC,ALL
from flask import Flask, make_response,render_template,url_for,redirect,request,session,escape
from validusers import users
app = Flask(__name__)
IT = pymysql.connect(host='xx.xx.xx.xx', user='xxxxx', password='xxxxx',
db='xxxx')#Connect to the IT database
Others = pymysql.connect(host='xxxxx', user='xxxxxx', password='xxxxxx',
db='xxxxx')#Connect to the non IT database
a=IT.cursor() # Open Cursor for IT database
b=Others.cursor()#Open Cursor for non-IT database
**#app.route('/')
#app.route('/login',methods=['GET', 'POST'])
def login():
error=None
if request.method =='POST':
#if not request.form['username']:
#error='You forgot to enter "Username", please try again'
#return render_template('login.html',error=error)
if request.form['username'].lower() not in users:
error='You are not authorized to view this page !!'
return render_template('login.html',error=error)
#if not request.form['password']:
#error='You forgot to enter "Password", please try again'
#return render_template('login.html',error=error)
#else:
#s = Server('appauth.corp.domain.com:636', use_ssl=True, get_info=ALL)
#c = Connection(s,user=request.form['username'],password=request.form['password'],check_names=True, lazy=False,raise_exceptions=False)
#c.open()
#c.bind()
#if (c.bind() != True) is True:
#error='Invalid credentials. Please try again'
#else:
#session['username'] = request.form['username'].lower()
#return redirect(url_for('index'))
return render_template('login.html',error=error)**
#app.route('/index',methods=['GET','POST'])
def index():
if 'username' in session:
return render_template('index.html')
Filename = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Desktop\RosterUnified.csv" # Create/write a CSV file in the user's desktop
Filename1=os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Desktop\RosterCurrentMonth.csv"
d=open(Filename, 'w',newline='\n') #Format for CSV input
c = csv.writer(d)
c.writerow(["Manager NT ID"," Vertical Org","Employee ID" ]+ dayssl)# Write the header list of strings in the first row
for row in result_IT:
c.writerow(row)#Write output for IT to csv
d.close()
#result_IT and result_Oters part of code is ommitted
e=open(Filename, 'a',newline='\n')
f= csv.writer(e)
for row in result_Others:
f.writerow(row)# Append to the existing CSV file with non IT data
e.close()
x=session['username']
sql="select verticalorg from tbl_employeedetails where empntid=(%s)"
args=x
a.execute(sql,args)
b.execute(sql,args)
c=a.fetchall()
d1=b.fetchall()
s=c+d1
q=[x[0] for x in s]
sql1="select role from tbl_employeedetails where empntid=(%s)"
a.execute(sql1,args)
b.execute(sql1,args)
c1=a.fetchall()
d2=b.fetchall()
Role=c1+d2
r=[x[0] for x in Role]
if r=='O':
if q==27:
f1=open(Filename,'r',newline='\n')
f2=open(Filename1,'w',newline='\n')
reader = csv.DictReader(f1)
writer = csv.writer(f2)
writer.writerow(["Manager NT ID"," Vertical Org","Employee ID" ]+ dayssl)
rows = [row for row in reader if row['Vertical Org'] == 'HR']
writer.writerow[row in rows]
elif q==2:
f1=open(Filename,'r',newline='\n')
f2=open(Filename1,'w',newline='\n')
reader = csv.DictReader(f1)
writer = csv.writer(f2)
writer.writerow(["Manager NT ID"," Vertical Org","Employee ID" ]+ dayssl)
f2.close()
z=open(Filename1)
with z as f:
p = f.read()
else:
z=open(Filename)
with z as f:
p = f.read()
#app.route('/csv/')
def download_csv():
csv = p
response = make_response(csv)
cd = 'attachment; filename=RosterCurrentMonth.csv'
response.headers['Content-Disposition'] = cd
response.mimetype='text/csv'
return response
z.close()
os.remove(Filename)
#app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('login'))
app.secret_key ='secret key generated'
if __name__=='__main__':
context=('RosterWeb.crt','RosterWeb.key')
app.run(ssl_context=context, threaded=True, debug=True)
getting the error:
Traceback (most recent call last):
File "roster.py", line 175, in <module>
x=session['username']
File "C:\Users\dasa17\Envs\r_web\lib\site-packages\werkzeug\local.py", line 37
3, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
File "C:\Users\dasa17\Envs\r_web\lib\site-packages\werkzeug\local.py", line 30
2, in _get_current_object
return self.__local()
File "C:\Users\dasa17\Envs\r_web\lib\site-packages\flask\globals.py", line 37,
in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
You need to place the code you want to run before any routing is done in a function and use the before_first_request decorator on it. It will be executed before your first request is done and you can make use of your session variable from there.
#app.route('/')
def index():
# ... index route here ...
pass
#app.before_first_request
def init_app():
# ... do some preparation here ...
session['username'] = 'me'
How do I telnet to a box and have it echo what I typed in to verify
I'm truly logged in?????????
telnet = telnetlib.Telnet()
host = "10.59.50.171"
newline = "\n"
telnet = telnetlib.Telnet(host, '23')
telnet.read_until("Username: ".encode())
telnet.write(username)
telnet.read_until("Password: ")
telnet.write(password)
user_acct = {'ADMIN':'PASSWORD','READONLY':'PASSWORD'}
if username in user_acct and password == user_acct[username]:
print('Correct Login')
else:
print('Invalid Login... Please Try Again')
This is an example of how to use the latest pexpect to control a telnet session:
from pexpect import fdpexpect
import pexpect
import select
import socket
class SocketSpawn(fdpexpect.fdspawn):
def read_nonblocking(self, size=1, timeout=-1):
if timeout == -1:
timeout = self.timeout
rlist = [self.child_fd]
wlist = []
xlist = []
rlist, wlist, xlist = select.select(rlist, wlist, xlist, timeout)
if self.child_fd not in rlist:
raise pexpect.exceptions.TIMEOUT('Timeout exceeded.')
return super(fdpexpect.fdspawn, self).read_nonblocking(size)
if __name__ == '__main__':
username = 'username'
password = 'password'
host = '10.59.50.171'
port = 23
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
session = SocketSpawn(s, timeout=10)
session.expect_exact('Username: ')
print session.before
session.write("%s\n" % username)
session.expect_exact('Password: ')
print session.before
session.write("%s\n" % password)
try:
session.expect_exact(pexpect.EOF)
except pexpect.TIMEOUT:
pass
print session.before
You will need the SocketSpawn class to fix a defect that was introduced in the latest versions of pexpect. However, this should also work with older versions of pexpect.
So I am really new to server and client code with python and I am doing this project from this book which asks me to do a couple of things. One of them is to transfer all the files so that the client can see them clearly. Here is the code.
Server:
import socket
from PIL import ImageGrab
import sys
sys.path.append(r'C:\Users\Home\Documents\python\new_project')
import pyperclip
import shutil
import glob
import subprocess
host = socket.gethostname()
port = 12346
server_socket = socket.socket()
server_socket.bind((host, port))
Server_online = True
while Server_online:
server_socket.listen(2)
client_socket, client_addr = server_socket.accept()
client_name = client_socket.recv(1024)
if client_name == "Screen Shot":
im = ImageGrab.grab()
f = open('C:\Users\Home\Documents\screen.txt')
i = int(f.read())
f.close()
im.save(r"C:\Users\Home\Documents\python\new_project\screen" + str(i) +'.jpg' )
i = i + 1
f = open('C:\Users\Home\Documents\screen.txt', 'w')
f.write(str(i))
f.close()
client_socket.send("Picture taken")
elif client_name == "Copy":
while 1:
try:
data = client_socket.recv(1024)
Copied = pyperclip.copy(data)
client_socket.send("text copied.")
break
except:
client_socket.send("Failed to copy")
elif client_name == "Paste":
pasting = pyperclip.paste()
elif client_name == "Show files":
while 1:
files = client_socket.recv(1024)
files_list = glob.glob("C\\Users\\Home\\Documents\\" + files + "\\*.*")
client_socket.send(**files_list**)
break
elif client_name == "Exit":
client_socket.sendall("Exting server...")
client_socket.close()
client_socket.close()
server_socket.close()
Client:
import socket
import time
import glob
host = socket.gethostname()
port = 12346
client_socket = socket.socket()
client_socket.connect((host, port))
client_connected = True
while client_connected:
print '''Pick What you want to do.(Screen Shot, Copy, Paste,
Show files, Open files, Copy files, Exit )'''
request = raw_input()
if request == "Screen Shot":
print "Screen shot in 5 seconds"
for i in range(5,0,-1):
print i
time.sleep(1)
client_socket.send("Screen Shot")
print client_socket.recv(1024)
elif request == "Copy":
client_socket.send("Copy")
print "what do u want to be copied:"
Copied = raw_input()
client_socket.send(Copied)
print client_socket.recv(1024)
elif request == "Exit":
client_socket.send("Exit")
print client_socket.recv(1024)
break
elif request == "Paste":
client_socket.send("Paste")
elif request == "Show files":
client_socket.send("Show files")
print "What files do you want to send?"
files = raw_input()
client_socket.send(files)
outcome = client_socket.recv(1024)
try:
for files in outcome:
print files
except:
print "no outcome"
else:
print "Not one of the requests. Enter again."
client_socket.close()
So as you can see it is really easy stuff but what i am stuck on is how to transfer the variable in the "Show files" (server) part where the server sends the client a list of the listed files. (its bloded).
If you can help me out that would be great I have been stuck on this for weeks
Well this is old. I solved this problem later on.
all you need to do is this (better to do it with the struct library):
on the server:
file_list = '\n'.join(file_list)
files_list_len = len(files_list)
client_name.send(files_list_len)
client_name.send(file_list)
client side:
recv_size = client_socket.recv(4)
files = client_socket.recv(recv_size).split("\n")
I know there are tons of posts about the AttributeError: NoneType... but they don't seem to apply. My code has been working for years, and this week i am getting this error. Also, I am not an expert coder.
I checked the Python Path, and it seems normal:
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Python27;C:\Python27\Scripts
When i try to edit the code in Komodo IDE, the autocomplete works fine, e.g., self.ser.write(string) has the write in the suggestion menu.
It is as if it can't find the library. Is that right? How can that be?
I am using XP.
Thanks!
OK, i figured it out. I traced the failure to instantiation of opening a COM port (debugging in Komodo IDE was very helpful). It failed to open the port, and while the wrapper (below) for pyserial caught the error, my code didn't do anything about it. So when i tried to use serial methods, i.e. `ser.write()' (where ser is my port instance) i get the AttributeError.
The port failed to open because of the box on the other end wasn't communicating properly. Resetting this box (a motor controller) fixed the problem.
The wrapper I use for PySerial appears to be in-house code---short but useful. I am sharing it here:
SerialIO: Wrapper for PySerial
#----------------------------------------------------------------------
# serialIO: wrappers for pyserial module for exception handling, etc.
#----------------------------------------------------------------------
# depends on http://pyserial.sourceforge.net/
import serial
import sys
import time
##################################### serial handlers
# all serial commands except stop are filtererd through this
class serialIO():
def __init__(self,port, baudrate, timeout=0.0,echo=False,rtscts=False):
self.port = port
self.br = baudrate
self.to = timeout
self.echo = echo
self.rtscts = rtscts
self.stdout = False
self.ser = None
self.status = "OK"
self.reopen()
def reopen(self):
# first close it if it's already open
if self.ser:
try:
self.ser.close()
except serial.SerialException, v:
self.status = "error"
# do we want stdout (for debug)?
if self.port == "stdout":
self.stdout = True
self.ser = sys.stdout
else: # nope, actually open the prort
try: # xonxoff=True hoses binary polling of Faulhabers!
self.ser = serial.Serial(self.port, self.br,
timeout=self.to,
rtscts =self.rtscts,
xonxoff=False)
except serial.SerialException, v:
self.status = "error"
print str(v)
return(self.status)
def echo(self,str):
pass
# write the given string to the serial device, catching exceptions
def safewrite(self,string,flush=True):
try:
result = self.ser.write(string)
if flush:
if self.stdout:
sys.stdout.flush()
else:
self.ser.flushOutput()
except serial.SerialException, v:
print str(v)
return(-1)
return(result)
def REALLYflushInput(self):
""" because ser.flushInput() doesn't seem to work :/"""
if self.stdout:
return
self.ser.flushInput()
time.sleep(0.01)
#self.ser.flushInput()
readstr = ""
incount = self.ser.inWaiting()
while (incount > 0):
readstr += self.ser.read(incount)
time.sleep(0.01)
incount = self.ser.inWaiting()
# write the given string to the serial device
def write(self,string,flush=True):
self.ser.write(string)
if flush:
if self.stdout:
sys.stdout.flush()
else:
self.ser.flushOutput()
def read(self,nb):
return(self.ser.read(nb))
# returns number of bytes successfully read, -1 if error
def saferead(self):
if self.stdout:
return("",0)
nread = 0
try:
incount = self.ser.inWaiting()
except serial.SerialException, v:
incount = 0
raise
rstr = ""
while (incount > 0):
try:
rstr += self.ser.read(incount)
except serial.SerialException, v:
print str(v)
return(rstr,-1)
nread = nread + incount
incount = self.ser.inWaiting()
return(rstr,nread)
def readstr(self):
incount = self.ser.inWaiting()
readstring = ""
while (incount > 0):
readstring += self.ser.read(incount)
incount = self.ser.inWaiting()
if self.echo:
self.log("read %s" % readstring)
return readstring
# resturn a list of available serial devices
def GetPortList(plist):
# for port in portlist:
if len(plist) < 1:
# if no list of portnames, make one
plist = ['COM2','COM3','COM4','COM5']
OKports = []
for port in plist:
ser = None
try:
ser = serial.Serial(port, 9600)
except serial.SerialException, v:
#print str(v)
pass
else:
OKports.append(ser.name)
finally:
if(ser):
ser.close()
return OKports
if __name__ == '__main__':
plist = GetPortList([])
print str(plist)
It looks more as if your variable self.ser has NoneType, so you might need to take a look at the place where you initialize self.ser in your class.
Edit: Looking around it seems that the library you are using is pyserial2.7 right? I have seen at the documentation here a class called just Serial, which also takes as input a port and a baudrate, so I guess it might be the class you need. Maybe you are getting NoneType because that SerialIO is deprecated. I have not been able to find it, but that does not mean it doesn't exist. Objects of class Serial also have a write method according to this documentation.