connect telnet with python - python

I tried to connect bbs with python's library "telnetlib", try to make a robot to answer
the message. While I answered the message,the robot return more than 1 message.These are my
code.
# -*- coding: cp950 -*-
import telnetlib,random
#f= open("ans.txt","r")
ans = [b"oao", b"xd"]
'''while True:
line = f.readline()
if line = "":
break
ans.append(line)
'''
tn = telnetlib.Telnet("ptt.cc")
tn.read_very_eager()
tn.write(b"*****\r\n") # this is where i enter my username
tn.read_very_eager()
tn.write(b"*****\r\n") # this is wher i enter my password
tn.read_very_eager()
tn.write(b"\r\n")
while True:
if tn.read_very_eager() != "" :
tn.write(b"")
tn.read_very_eager()
tn.write(b"su\r\n")
tn.read_very_eager()
tn.write(b"\r\n")
tn.read_very_eager()
tn.write(b"\r\n\r\n←")
tn.read_very_eager()
tn.read_very_eager()
for i in range(0,1000000):
x = 1

First, I have absolutely no experience with telnet.
Looking at the Python documentation on telnetlib I can see some differences between your code and the example at the bottom of the docs page. The major difference is they wait for a prompt to log-in or provide a password. Even if your read_very_eager should do the same thing, it's more clear to read_until. It could solve your problem, or give you a hint about it.
Try adapting the example to fit your needs.
import sys
import telnetlib
HOST = 'ptt.cc'
user = 'username'
password = 'pass123'
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
# Do anything you need to here.
# If your server will accept these, try them first to isolate the problem
tn.write("ls\n")
tn.write("exit\n")
print tn.read_all()
As mentioned by MatthieuW, you could sleep with the time library.
from time import sleep
print 'Start'
sleep(1)
print 'One second later'

Related

How to execute a command & respond to multiple inputs using python subprocess?

I am trying to understand how to execute a command/program using python subprocess module & respond to the prompt by giving input.
Sample Program Program1.py which can take multiple input's:
arr1=[]
username = input("Enter your username1 : ")
password = input("Enter your password1 : ")
arr1.append((username,password))
username = input("Enter your username2 : ")
password = input("Enter your password2 : ")
arr1.append((username,password))
username = input("Enter your username3 : ")
password = input("Enter your password3 : ")
arr1.append((username,password))
username = input("Enter your username4 : ")
password = input("Enter your password4 : ")
arr1.append((username,password))
for item in arr1:
print("username:",item[0],"Password:",item[1])
I have written another program called Execute_Program1.py
import subprocess
proc = subprocess.Popen('python Program1.py',stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE,shell=True,universal_newlines=True)
print(proc.poll())
while proc.poll() is None:
print(proc.stdout)
proc.stdin.write('inputdata\n')
But this program is not able to execute the Program1.py. I have read many posts related to this. As per the information I have got proc.poll() return's None then the command executed by Popen is still active.
But my program is giving the following output:
None
<_io.TextIOWrapper name=4 encoding='cp1252'>
I am using Python version 3.7.4. Could anyone please help me with some inputs where I am doing mistake?
Thanks in advance.
I could not get it to work with subprocess at this time but I wanted you to have an ASAP working solution using the os module in case you need this quickly and are not absolutely required to use the subprocess module...
First add this line to the end of Program1.py, with no indentation, to prevent the command window from exiting before you have a chance to see the output:
input("Press <enter> to continue")
Next, replace your entire code in Execute_Program1.py with the following:
import os
os.system("python Program1.py 1")
This worked beautifully in Python 3.8.1 on win10pro.

Python 3 Print output from try statement on the same line and I am trying to learn threading

import os
import time
import threading
import urllib.request
def message(msg):
print(time.strftime('[%H:%M:%S]'), msg)
def check(proxy):
proxy_support = urllib.request.ProxyHandler({'https':proxy})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
message("Trying => "+proxy)
try:
urllib.request.urlopen("https://www.google.com", timeout=5)
print("Working")
with open("CheckedProxies.txt", "a") as appe:
appe.write(proxy.replace("\n","") + "\n")
except:
print("Not Working")
pass
try:
proxies = open("/home/zion/Desktop/proxies.txt", "r").readlines()
except:
message("File Empty Exiting!")
exit()
if proxies == "":
print("File Empty, Enter Proxies")
newtxt = open("CheckedProxies.txt","w")
message("~ Loading "+ str(len(proxies)) +" Proxies!")
time.sleep(1)
for proxy in proxies:
check(proxy)
os.exit(CTRL-C)
message("Done Checking Proxies!")
I am trying to get the Not working to print on the same line as Trying proxy....my current output is:
[23:20:51] ~ Loading 1598 Proxies!
[23:20:52] Trying => 1.0.135.34:8080
Not Working
[23:20:53] Trying => 1.10.236.214:8080
Not Working
[23:20:53] Trying => 103.122.255.18:8080
I am trying to get it to print like this
[23:20:53] Trying => 127.0.0.1:8080 Not Working!
I have tried to "print("Not Working", end='')"
but it prints out like this``
Not Working[23:07:30] Trying => 1.10.236.214:8080
I am not sure how to get the Not working to print after the trying and proxy....
I am also trying to learn how to use the threading module but am having trouble....
I want my program to open multiple threads testing my proxys... thank you in advance for any help.
In regards to threading, the best way to do it here is to use a Multiprocessing Pool.
from multiprocessing import Pool
And then instead of:
for proxy in proxies:
check(proxy)
Use:
p=Pool(5)
p.map(check,proxies)
For making them all on one line, I would add the outputs to a string, then at the end of the function print it out.
Regarding the printing, it seems that you want to print without an automatic newline and you have worked out to use end
print("Hello ", end = '')
print("World! ")
you say
I have tried to "print("Not Working", end='')" but it prints out like
this``
but it seems to me that the problematic print() is in
def message(msg):

Using pexpect to automate IP validations

My end goal is to log into a switch, get the CDP neighbor details written to a file. parse out the IP addresses and run pings on the IP address and output that to a file. I've searched the forums and found nothing really pertaining to switches. Mainly servers, and I've adapted from there. But Now I am stuck.
I get as far as getting logged into a switch and my login prompts seem to be written to a file but nothing else.
Please excuse errors in the code. Also, the second try block is a work in progress. I am new to python and learning as I go. I am open to any and all critiques and suggestions. I want to know what I have done incorrectly, fix it, and build from there.
Thanks in advance!
import pexpect
import getpass
import sys
import re
import os
import time
try:
switch = raw_input("Host: ")
un = raw_input("Username: ")
pw = getpass.getpass("Password: ")
options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'
prompt = "#"
connection_string = ("ssh %s#%s %s" % (un,switch,options))
child = pexpect.spawn(connection_string, timeout=5)
file_output = open('switch_output.txt','wb+')
child.logfile = file_output
rva12 = "";
child.expect(re.escape("password:"))
time.sleep(1)
child.sendline(pw)
time.sleep(1)
child.expect(prompt)
time.sleep(1)
child.sendline("no page")
time.sleep(1)
child.expect(prompt)
child.sendline("show cdp nei det")
time.sleep(1)
child.expect(prompt)
child.before
file_output.close()
except Exception as e:
print("Failed on login")
print(sys.exc_info()[0].__name__,
os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename),
sys.exc_info()[2].tb_lineno)
print(e)
try:
f = open('switch_output.txt', 'r')
pattern_one = re.compile('.*A\d\n|\:\s\d{2,}\.\d{2,}\.\d{1,}.\d{1,}?')
for line in f:
matches = []
if pattern_one.search(line):
matches.append(line.split(':', 1)[-1].strip())
mp = re.compile('\d{2,}\.\d{2,}\.\d{1,}.\d{1,}')
with open('MDF1.txt', 'wb+') as file:
for match in matches:
if mp.search(match):
file.write(match+'\n')
file.close()
for line in open('MDF1.txt','r'):
child.expect(prompt)
child.sendline('ping '+ line)
time.sleep(10)
except Exception as e:
print(sys.exc_info()[0].__name__,
os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename),
sys.exc_info()[2].tb_lineno)
print(e)

Python Serial Read returning strange values

I have a small python example I got off another website. I am trying to understand how to read from serial using it.
I am sending a message from a FRDM K64f board over serial and the python program reads this but returns a strange values, below is an example of one of them:
YVkJ�ZC
My python code:
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(input + '\r\n')
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
This is my code for the board:
int main(){
Serial pc(USBTX, USBRX);
pc.baud(9600);
while(1){
char c = pc.getc();
if((c == 'w')) {
pc.printf("Hello");
}
}
}
The exact return I get is this:
Enter your commands below.
Insert "exit" to leave the application.
>> w
>>YVkJ�ZC
>>
Managed to solve this.
My declaration of serial didn't seem to be working properly.
Went back to pyserial documentation and declaring my serial like below and using readline() solved the problem.
ser = serial.Serial('/dev/ttyACM0')

Python program to connect to console via telnetlib

Hi I am a tcl person trying to do a day to day activity in Python in order to get familiarity with a new language and to compare Python with tcl. No one wants tcl programs anymore :)
Ok , So I have come with a code to automate this typical activity I would do to clear a console line .
$ telnet 172.28.247.240
Trying 172.28.247.240...
Escape character is '^]'.
User Access Verification
Password:
labc-f18-ts>en
Password:
labc-f18-ts#clear line 66
[confirm]
[OK]
My Code looks like this:
import getpass
import sys
import telnetlib
a_tuple = [ ('172.28.247.240' , 66)]
HOST = j[0]
user = "admin"
password = "1234"
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.read_until("labc-f18-ts>")
tn.write ("en" +"\n")
tn.read_until("labc-f18-ts#")
tn.write("clear line %d" %j[1])
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
But I dont seem to get any output and dont know if it actually cleared the lines - there is no output whatsoever. Please help.
Also is there anything like pexpect that I should be working with rather what I have above?
import telnetlib
# ...
a_tuple = [('172.28.247.240', 66)]
HOST = a_tuple[0] # do you mean to use 'a_tuple' instead of 'j'?
# ...
tn = telnetlib.Telnet(HOST[0], HOST[1]) # <-- pass the port, I don't think this accepts tuples of hostname/ip and port
# ...
Should part of your code looks like above instead?
Also, I would normally use carriage return (\r) instead of new line (\n) when sending commands. Some host are picky about this.

Categories

Resources