Python telnet client - python

Everyone, hello!
I'm currently trying to use Telnetlib (https://docs.python.org/2/library/telnetlib.html) for Python 2.7 to communicate with some external devices.
I have the basics set up:
import sys
import telnetlib
tn_ip = xxxx
tn_port = xxxx
tn_username = xxxxx
tn_password = xxxx
searchfor = "Specificdata"
def telnet():
try:
tn = telnetlib.Telnet(tn, tn, 15)
tn.set_debuglevel(100)
tn.read_until("login: ")
tn.write(tn_username + "\n")
tn.read_until("Password: ")
tn.write(tn_password + "\n")
tn.read_until(searchfor)
print "Found it!"
except:
print "Unable to connect to Telnet server: " + tn_ip
telnet()
And I'm trying to go through all of the data it's outputting (which is quite a lot) until I catch what I need. Although it is logging in quite fine, and even finds the data I'm looking for, and prints my found it message, I'm trying for a way to keep the connection with telnet open as there might be other data (or repeated data) i would be missing if I logged off and logged back in.
Does anyone know how to do this?

Seems like you want to connect to external device once and print a message each time you see a specific string.
import sys
import telnetlib
tn_ip = "0.0.0.0"
tn_port = "23"
tn_username = "xxxxx"
tn_password = "xxxx"
searchfor = "Specificdata"
def telnet():
try:
tn = telnetlib.Telnet(tn_ip, tn_port, 15)
except:
print "Unable to connect to Telnet server: " + tn_ip
return
tn.set_debuglevel(100)
tn.read_until("login: ")
tn.write(tn_username + "\n")
tn.read_until("Password: ")
tn.write(tn_password + "\n")
while True:
tn.read_until(searchfor)
print "Found it"
telnet()

Related

Python Keylogger - Not keeping Keyboard Listener open upon execution from CMD

BEFORE WE START...
I am fairly new to Python and any assistance or insight would be absolutely great.
This is NOT malicious keylogger, nor a virus, and is going to be used by my company to monitor network PCs for security purposes ONLY. It does not send logs and stores the files locally. It will not attempt to remain hidden. I am an enterprise programmer with no malicious intent. Users will be made aware that keystrokes are being monitored, and logs are stored in the user's home directory.
My Python works perfectly fine and as expected in the IDLE editor. However upon running the code from the command line, it does not continue to execute and the script exits.
I have attempted to port my code line by line to a different working version, removing any extra content. Adding a single line break or import appears to completely break the script.
The following code works and does not exit upon execution. It continues to log and works as expected. When ran from CMD, the process remains open:
from os.path import expanduser
home = expanduser("~")
from pynput.keyboard import Key, Listener
import logging
log_dir = r"{}/".format(home)
logging.basicConfig(filename = (log_dir + "log.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
def on_press(key):
logging.info(str(key))
with Listener(on_press=on_press) as listener:
listener.join()
However the following code does not continue to log after execution and the program exits:
from pynput.keyboard import Key, Listener
import time
import os
import random
import requests
import socket
import platform
import win32api
import wmi
import urllib.request
import logging
from os.path import expanduser
homeDir = expanduser("~")
SystemType = platform.system()
SystemArchitecture = platform.machine()
SystemPlatform = platform.platform()
SystemProcessor = platform.processor()
VolumeInformation = win32api.GetVolumeInformation("C:\\")
HostName = socket.gethostname()
SystemWMI = wmi.WMI()
publicIP = requests.get('https://api.ipify.org').text
privateIP = socket.gethostbyname(socket.gethostname())
user = os.path.expanduser('~').split('\\')[2]
datetime = time.ctime(time.time())
file = open(homeDir + "\logger.txt", "w+")
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("Hostname: " + HostName)
file.write("Hostname: " + HostName + "\n")
print("User: " + user)
file.write("User: " + user + "\n")
print("Public IP: " + publicIP)
file.write("Public IP: " + publicIP + "\n")
print("Private IP: " + privateIP)
file.write("Private IP: " + privateIP + "\n")
for interface in SystemWMI.Win32_NetworkAdapterConfiguration (IPEnabled=1):
print("MAC Address: " + interface.MACAddress)
file.write("MAC Address: " + interface.MACAddress + "\n")
print("Interface Description: " + interface.Description)
file.write("Interface Description: " + interface.Description + "\n\n")
print()
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
if(SystemType == "Windows"):
print("System Type: " + SystemType)
file.write("System Type: " + SystemType + "\n")
print("System Architecture: " + SystemArchitecture)
file.write("System Architecture: " + SystemArchitecture + "\n")
print("System Platform: " + SystemPlatform)
file.write("System Platform: " + SystemPlatform + "\n")
print("System Processor: " + SystemProcessor)
file.write("System Processor: " + SystemProcessor + "\n\n")
DriveList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ActiveDrives = ['%s:' % d for d in DriveList if os.path.exists('%s:' % d)]
DRIVE_TYPES = {
0 : "Unknown",
1 : "No Root Directory",
2 : "Removable Disk",
3 : "Local Disk",
4 : "Network Drive",
5 : "Compact Disc",
6 : "RAM Disk"
}
print()
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("Drives In Use: ")
file.write("Drives In Use: \n")
print(ActiveDrives)
file.write(str(ActiveDrives) + "\n\n")
print()
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("Drive Types: ")
file.write("Drive Types: \n\n")
for drive in SystemWMI.Win32_LogicalDisk ():
print(drive.Caption, DRIVE_TYPES[drive.DriveType])
file.write(drive.Caption)
file.write(DRIVE_TYPES[drive.DriveType] + "\n")
print()
file.write("\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("C:\\ Volume Information")
file.write("C:\\ Volume Information: \n")
print(VolumeInformation)
file.write(str(VolumeInformation) + "\n\n")
print()
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("OS Instance Information: ")
file.write("OS Instance Information: \n")
for os in SystemWMI.Win32_OperatingSystem():
print(os)
file.write(str(os) + "\n")
print()
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("Logging keystrokes...")
file.write("Logging keystrokes...\n\n")
file.close()
log_dir = r"{}/".format(homeDir)
logging.basicConfig(filename = (log_dir + "logger.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
def on_press(key):
print(key)
logging.info(str(key))
with Listener(on_press=on_press) as listener:
listener.join()
Even adding a single import to the working version breaks it. There are no exceptions thrown.
The code is expected to continue to log keystrokes after execution, however is exiting without any error codes. It works as expected in IDLE and continues to log until IDLE is closed. However when ran from CMD it closes right after it outputs "Logging Keystrokes...".
Help?
Come to find out, it was the antivirus on the PC that was causing the program to crash. This works normally and as expected from the getgo.

python sockets, trying to make a log in interaction betwen server and client

Hello so i have my server with a database (dictironay) and another passworddatabase
import socket
import sys
from _thread import *
host = ""
port = 8000
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket Created")
try:
serversocket.bind((host, port))
except socket.error as e:
print(str(e))
sys.exit()
database = {"name1" :{"hair" : "red", "size" : 1.50}}
password_database = {"name1": "1234",
"name2": "4321"}
def client_thread(conn): #threader client
welcome = "Welcome to the server. Type something and hit enter \n"
conn.send(welcome.encode("UTF-8"))
login(conn)
while True: # NOT IMPORTANT KEEP READING
data = conn.recv(24)
reply = data.decode("UTF-8")
if reply == "1":
menu1 = "Menu 1: Buy \n"
conn.send(menu1.encode("UTF-8"))
else:
wrong = "wrong option \n"
conn.send(wrong.encode("UTF-8"))
def login(conn): #MY LOGIC PROBLEM IS HERE
log = "Log in MENU: \n"
logi = log.encode("UTF-8")
conn.send(logi)
us = "Username: \n"
use = us.encode("UTF-8")
conn.send(use)
userr = conn.recv(24)
user = userr.decode("UTF-8")
pa = "Password: \n"
pasw = pa.encode("UTF-8")
conn.send(pasw)
passr = conn.recv(24)
passw = passr.decode("UTF-8")
tries = 0
while tries < 3:
if user in passwordDictionary and passwordDictionary[user] == passw:
print("Logged in")
menu()
else:
print("Wrong Username Or Password \n")
tries += 1
print("You failed the login too many times, blocking you out")
conn.close()
while 1: # NOT IMPORTANT
conn, addr = serversocket.accept()
print("Connected with " + addr[0] + ":" + str(addr[1]))
start_new_thread(client_thread, (conn, ))
serversocket.close()
Whats working:
The server is working fine, i'm having troubles doing the login on the client side.
client.py ==> client DOESNT go into the if data == Log in menu
is there a better way to do this?
#! /usr/bin/python3
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8000))
print("Connected")
datae = clientsocket.recv(24)
data = datae.decode("UTF-8")
clientsocket.send(datae)
while data != "!q":
if data == "Log in MENU: \n":
usere = input()
user = usere.encode("UTF-8")
clientsocket.send(user)
What would be the best way to create an log in interaction with the server?
the server has the usernames and passwords, i need to log in and then i need to edit the database depending on what user was chossen, but i'm having a hard time doing the algorithm
theres problems with the code you provided... however ill assume it actually works for you somehow and rather than copy paste you manually typed it
you are recieveing the first message here
datae = clientsocket.recv(24)
data = datae.decode("UTF-8") # GOT A MESSAGE
You then have the message datae = b'Welcome to the server. '
which does not match "Log in MENU: \n", and data != "!q" so it goes back into your loop and checks if data == "Log in MENU: \n" it doesnt so it repeats ... but you never get the next message instead try something like this second message
data = ""
while data != "!q":
if data == "Log in MENU: \n":
usere = input()
user = usere.encode("UTF-8")
clientsocket.send(user)
data = clientsocket.recv(24).decode("UTF-8") # GET THE NEXT MESSAGE!
but even then you are going to have problems because your server continues to write so you will get something like "Log in MENU: \nUsername" or something .... basically you need to work out a better message passing scheme than recv(24)
To avoid Errors try using a header with something like 64 Bytes wich always is the first message send. This Header is then used to send the actual length of the following message to the server. For example:
def send_response(conn, msg):
message = msg.encode(FORMAT)
send_length = len(str(len(message)).encode(FORMAT))
res_len = bytes(len(message)) + (b' ' * (HEADER - send_length))
print(f"[SENDING MESSAGE] {msg}")
conn.send(res_len)
conn.send(response)

Cannot connect to imap server on python

I'm a networking student who has little programming experience and I have simple project on my hands where I need to make a simple notification that notifies the user when an email arrives in gmail. I have been trying to get this to work for the last few weeks and I am honestly stuck and struggling. I'm using the code below and I think the problem is the authentication bit, where I can't connect to the server. All help is appreciated.
import imaplib
import re
import time
import subprocess
## enter your account details bellow!
imapServer = "imap.gmail.com"
port = "993"
username = "example#gmail.com"
password = "password"
##how often to check ? give interval in seconds! Checking too often might performance and stability.
checkInterval = 120
Mailbox = imaplib.IMAP4_SSL(imapServer, port)
rc,resp = Mailbox.login(username,password)
if rc == 'OK':
print("Connected to mail-server " + imapServer)
rc, message = Mailbox.status('INBOX', "(UNSEEN)")
unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
oldValue = 0
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
file.write(str(unreadCount))
file.close
while(1):
rc, message = Mailbox.status('INBOX', "(UNSEEN)")
unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
oldValue = int(file.readline())
file.close()
if (unreadCount>oldValue):
subprocess.call(["notify-send", "-u", "low", "low", "t", "5000", "New email!", "New email!",
"You have " + str(unreadCount) + " unread " + "emails!" if unreadCount > 1 else "email!",
"--icon=email"])
if oldValue != unreadCount:
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
file.write(str(unreadCount))
file.close()
time.sleep(checkInterval)
else :
print('Fail to connect')
Mailbox.logout()
file.remove()

python - function not returning full output

Im trying to get the model no of a switch from show inventory then set a integer to the no of ports the switch has. ive tried to make the result go onto one line and then search that with regex (the regex works i tested it on http://regexr.com/)
It doesn't look like my function is returning the full inventory, its getting cut off. it should return the below
Switch#sh inventory
NAME: "1", DESCR: "WS-C2960X-24PS-L"
PID: WS-C2960X-24PS-L , VID: V01 , SN: XXXXX
This is the output im getting
Switch#
Switc
Object is: terminal length 0
Switch#sh inventory
NAME:
Inventory is:
Port Count is: 0
and this is the script
#!/usr/bin/env python
import paramiko
import time
import sys
import re
# For debugging only
#paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
#
interface_regex = "interface GigabitEthernet[1-5]\/0\/"
def Send_Command_and_Get_Response(command, reponse, result):
# Send the su command
shell.send(command)
# Create a new receive buffer
receive_buffer = ""
while not reponse in receive_buffer:
# Flush the receive buffer
receive_buffer += shell.recv(1024)
# Print the receive buffer, if necessary
if result:
print receive_buffer
return receive_buffer
# VARIABLES THAT NEED CHANGED
ip = '10.X.X.X'
username = 'root'
password = 'XXXX'
port = 3010
# Create instance of SSHClient object
client = paramiko.SSHClient()
# Make sure that we add the remote server's SSH key automatically
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# initiate SSH connection
client.connect(ip, username=username, password=password,port=port, look_for_keys=False, allow_agent=False)
print "SSH connection established to %s" % ip
# Use invoke_shell to establish an 'interactive session'
shell = client.invoke_shell()
print "Interactive SSH session established"
time.sleep(1)
shell.send("\r\n")
output = shell.recv(1000)
print output
# Disable more
Send_Command_and_Get_Response("terminal length 0\n", "#", False)
objInv = Send_Command_and_Get_Response("sh inventory\n", "#", False)
strInv =""
strInv.join(objInv.splitlines())
intPort = 0
if (re.match("WS-C.*24", strInv)):
intPort = 24
elif (re.match("WS-C.*48", strInv)):
intPort = 48
print "Object is: " + objInv
print "Inventory is: " + strInv
print "Port Count is: " + str(intPort)
# Close the SSH connection
client.close()
replaced new lines and breaks and used find instead of regex and its fixex!
objInv = Send_Command_and_Get_Response("sh inventory\n", "#", False)
print "Object is: " + objInv
strInv = str(objInv)
strInv = strInv.replace('\n','').replace('\r','')
intPort = 0
if (strInv.find('WS-C') >-1 and strInv.find('-24') >-1):
intPort = 24
if (strInv.find('WS-C') >-1 and strInv.find('-48') >-1):
intPort = 48

Using Python 3.4 to Ping a network then report address, dns name, etc.

I wanted to create a Python program that does several things. Ping all addresses in a predefined network, gather the DNS information, write a file with IP address, DNS name, ping fail or pass, date. Then run and email the resulting file to myself once a week, every Friday. I have created this program and will post my own answer. I am new to Python and was able to get this written with the help from other answers posted on this site. Thanks to all those who contributed answers on this site. Hope the answer I post will help someone else.
#!/usr/bin/python3.4
#Above statement makes sure you are using version 3.4
#when multiple versions are installed. has to be the 1st line.
# Import modules
import subprocess
import socket
import errno
import time
import datetime
import ipaddress
today = datetime.date.today()
# define DNS lookup and error handling
# return none,none,none needed otherwise if no DNS record
# the routine errors out and the program stops
def lookup(addr):
try:
return socket.gethostbyaddr(addr)
except socket.herror:
return None, None, None
# Prompt the user to input a network address
# commented out the prompt for input so it can run unattended
# net_addr = input("Enter a network address in CIDR
format(ex.192.168.1.0/24): ")
net_addr = ('192.168.1.0/24')
# Create the network
ip_net = ipaddress.ip_network(net_addr)
# Get all hosts on that network
all_hosts = list(ip_net.hosts())
# Configure subprocess to hide the console window
# removed code due to errors not windows linux
# setup online and offline count variables
offCnt = 0
onCnt = 0
# Open file and or create if it doesn't exist.
# file to be overwritten each time the program is run.
file = open("lab-ip.doc","w")
# For each IP address in the subnet,
# run the ping command with subprocess.popen interface
# Grab the DNS information for each IP address
# Print to console add counters and write to file.
for i in range(len(all_hosts)):
output = subprocess.Popen(['ping', '-c', '2', str(all_hosts[i])],
stdout=subprocess.PIPE).communicate()[0]
name,alias,addresslist = lookup(str(all_hosts[i]))
if "Destination Host Unreachable" in output.decode('utf-8'):
print(str(all_hosts[i]), " Ping Fail", str(name), today)
file.write(str(all_hosts[i]) + " Ping Fail - " + str(name) + " " + str(today) + "\n")
offCnt = offCnt + 1
elif "Request timed out" in output.decode('utf-8'):
print(str(all_hosts[i]), " Ping Fail", str(name), today)
file.write(str(all_hosts[i]) + " Ping Fail - " + str(name) + " " + str(today) + "\n")
offCnt = offCnt + 1
else:
print(str(all_hosts[i]), " Ping Pass", str(name), today)
file.write(str(all_hosts[i]) + " Ping Pass - " + str(name) + " " + str(today) + "\n")
onCnt = onCnt + 1
print ("Pass count = ", str(onCnt))
file.write("Pass count = " + str(onCnt))
print ("Fail count = ", str(offCnt))
file.write(" Fail count = " + str(offCnt))
file.close()
# Import yagmail for the actual sending function
import yagmail
yag = yagmail.SMTP('Gmail-id', 'gmail-pswd')
yag.send('email#email.com', subject = "Lab-ip List",contents = 'lab-ip.doc')
yag.send('email2#email2.com', subject = "Lab-ip List",contents = 'lab-ip.doc')
#end

Categories

Resources