I'm working on a Telnet client. I started coding on my notebook(Windows) and at the finish I uploaded it on my server(Debian). Both systems works with Python 3. At my notebook the script works well, but on Debian, it does make errors.
The Code:
import telnetlib
import sys
try:
HOST = sys.argv[1]
user = sys.argv[3]
password = sys.argv[4]
cmd= sys.argv[5]
port=int(sys.argv[2])
tn = telnetlib.Telnet(HOST, port)
tn.read_until(b"username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"password: ")
tn.write(password.encode('ascii') + b"\n")
tn.write(cmd.encode('ascii') + b"\n")
except ConnectionRefusedError:
print('ERROR')
else:
print('OK')
Server(CraftBukkit server with RemoteToolKit):
Mar 05, 2014 12:39:58 PM net.wimpi.telnetd.net.ConnectionManager makeConnection
INFO: connection #1 made.
Unexpected error in shell!
java.net.SocketException: Connection reset
> at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:118)
> at java.net.SocketOutputStream.write(SocketOutputStream.java:159)
> at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
> at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
> at java.io.DataOutputStream.flush(DataOutputStream.java:123)
> at net.wimpi.telnetd.io.TelnetIO.flush(Unknown Source)
> at net.wimpi.telnetd.io.TerminalIO.flush(Unknown Source)
> at net.wimpi.telnetd.io.TerminalIO.write(Unknown Source)
> at com.drdanick.McRKit.Telnet.ConsoleShell.run(ConsoleShell.java:78)
> at net.wimpi.telnetd.net.Connection.run(Unknown Source)
Mar 05, 2014 12:39:58 PM net.wimpi.telnetd.net.ConnectionManager cleanupClosed
INFO: cleanupClosed():: Removing closed connection Thread[Connection1,5,]
Greets miny
EDIT: The error handling works now! THX # Wojciech Walczak
The client doesn't report errors, but the server reports errors. If I run the same code on Windows, it doesn't make errors.
...and are you sure you're using Python 3.3 or later? ConnectionRefusedError has been added in Python 3.3.
EDIT:
Given that your client works fine when launched from your laptop, and is catching ConnectionRefusedError on another machine, I would say that the problem is not the script itself. It's rather about server's telnet/firewall settings. Are other telnet clients working in the environment in which your script is failing?
The reason for the traceback when the server is offline is because you are trying to trap a non-existent exception (which is to say that the name ConnectionRefusedError has not yet been assigned a value).
Solely for its educational purpose I would remove the `try ... except ..." and let the error be raised Then hopefully you will find out exactly what exception is being raised.
As to the Java traceback, WTF?
The error is in the script. The telnet command on Linux works well.
I ran the code w/o try and except and it doesn't report errors.
I made some tests with byte strings.
If I run this code, the machines displays different strings.
Command:
print(b"Hello there!")
Windows:
b"Hello there!"
Linux:
Hello there!
Updated Code at Debian (Windows uses still the old code):
import telnetlib
import sys
if(True):
HOST = sys.argv[1]
user = sys.argv[3]
password = sys.argv[4]
cmd= sys.argv[5]
port=int(sys.argv[2])
tn = telnetlib.Telnet(HOST, port)
tn.read_until(b"username:")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"password:")
tn.write(password.encode('ascii') + b"\n")
tn.write(cmd.encode('ascii') + b"\n")
I tested the code at Windows and the telnet server can run the commands.
When I run the code at Debian, it doesn't say nothing, but the server says *Connection reset".
Related
I am not able to do telnet connection to my server. I am able to do it manually but through program it is not happening.
Below is the code from cmd which works fine -
C:\Users\Administrator>telnet <host>
WELCOME TO BRAMHA [PORT $ZTC0 #23 WINDOW $ZTN0.#PTUEAKH]
TELSERV - T9553J01 - (25JUN2009)
Available Services:
TACL EXIT
Enter Choice> TACL
TACL 1> logon super.super
Password:
Last Logon: 01 MAR 2022, 00:34
1> exit
Are you sure you want to stop this TACL (\BRAMHA.$X7A2)?yes
Connection to host lost.
C:\Users\Administrator>
I tried below Python code-
import os,re,telnetlib
host = "abc.com"
tn = telnetlib.Telnet(host)
tn.read_until(b"Enter Choice>", timeout=10) # <- add this line
# tn.read_until(b"> ", timeout=10) # if prompt has space behind
#tn.write(b"exit\n")
tn.write(b"tacl\n")
tn.read_until(b"TACL 1>", timeout=10)
tn.write(b"logon super.super\n")
tn.read_until(b"Password:", timeout=10)
tn.write(b"123abc\n")
tn.read_until(b"1>", timeout=10)
tn.write(b"exit\n")
tn.read_until(b"*?", timeout=10)
tn.write(b"yes\n")
x = tn.read_all()
print (x)
but while executing it is simply waiting and nothing is happening.
My requirement is ability to run a PowerShell script on a Windows 2012 server remotely, this has to be triggered from a Linux server using Python script.
Need suggestions on best way to handle this and also sample code (if possible).
Below are the steps I intend to achieve but i see it's not working as expected.
PowerShell scripts to be executed are already placed in Windows server (2012).
Python3 program running on Linux (CentOS) does SSH to Windows server (2012) using netmiko module.
sends the command (PowerShell command to execute script in remote Windows server) over the SSH connection.
I was able to connect to the remote Windows server using Python. But I don't see this method working as expected.
Need an effective and efficient way to achieve this.
from netmiko import ConnectHandler
device = ConnectHandler(device_type="terminal_server",
ip="X.X.X.x",
username="username",
password="password")
hostname = device.find_prompt()
output = device.send_command("ipconfig")
print (hostname)
print (output)
device.disconnect()
Nothing much is done for 'terminal_server" device type. You have to do manual passing at the moment.
Below is extracted from COMMON_ISSUES.md
Does Netmiko support connecting via a terminal server?
There is a 'terminal_server' device_type that basically does nothing post SSH connect. This means you have to manually handle the interaction with the terminal server to connect to the end device. After you are fully connected to the end network device, you can then 'redispatch' and Netmiko will behave normally
from __future__ import unicode_literals, print_function
import time
from netmiko import ConnectHandler, redispatch
net_connect = ConnectHandler(
device_type='terminal_server', # Notice 'terminal_server' here
ip='10.10.10.10',
username='admin',
password='admin123',
secret='secret123')
# Manually handle interaction in the Terminal Server
# (fictional example, but hopefully you see the pattern)
# Send Enter a Couple of Times
net_connect.write_channel("\r\n")
time.sleep(1)
net_connect.write_channel("\r\n")
time.sleep(1)
output = net_connect.read_channel()
print(output) # Should hopefully see the terminal server prompt
# Login to end device from terminal server
net_connect.write_channel("connect 1\r\n")
time.sleep(1)
# Manually handle the Username and Password
max_loops = 10
i = 1
while i <= max_loops:
output = net_connect.read_channel()
if 'Username' in output:
net_connect.write_channel(net_connect.username + '\r\n')
time.sleep(1)
output = net_connect.read_channel()
# Search for password pattern / send password
if 'Password' in output:
net_connect.write_channel(net_connect.password + '\r\n')
time.sleep(.5)
output = net_connect.read_channel()
# Did we successfully login
if '>' in output or '#' in output:
break
net_connect.write_channel('\r\n')
time.sleep(.5)
i += 1
# We are now logged into the end device
# Dynamically reset the class back to the proper Netmiko class
redispatch(net_connect, device_type='cisco_ios')
# Now just do your normal Netmiko operations
new_output = net_connect.send_command("show ip int brief")
I'm currently working a server-client setup in which I have two separate server scripts. One python script is responsible for running a SSH listener with Paramiko, and that script runs on one machine. I have another server script specifically acting as an SFTP server on another, separate machine, within the same range and subnet as the other one.
My client code is running on a windows 10 system. Both servers are running in unix environments (macOS and Ubuntu 16.04 respectively).
The SFTP server that I am running is aptly titled sftpserver, and is available at https://github.com/rspivak/sftpserver/.
The below code is actually the entirety of my client.py as it stands, minus the import statements.
key = paramiko.RSAKey.from_private_key_file('testkey.key')
transport = paramiko.Transport(('192.168.1.116', 10000))
transport.connect(username='root', password='toor', pkey=key)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.1.107', username='root', password='toor')
chan = client.get_transport().open_session()
chan.send("Hey man! I'm connected!")
print(chan.recv(1024))
def sftp(localpath, name):
try:
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(localpath, '/root/uploads/' + name)
sftp.close()
transport.close()
return "<+> Done uploading"
except Exception as e:
return str(e)
while True:
command = chan.recv(1024).decode()
ipdb.set_trace() // <-- debugging purposes only
if 'grab' in command:
_, path, name = command.split(' ')
chan.send(sftp(path, name))
else:
try:
CMD = subprocess.check_output(command, shell=True)
chan.send(CMD)
except Exception as e:
chan.send(str(e))
client.close()
Executing the grab command in my script looks like this:
grab C:\Users\xxx\testing.txt testing.txt
Now, if I write a path exactly like that (with the back slashes), it will append a second back slash after each one. So, the path I supplied now looks like C:\\Users\xxx\\testing.txt, and this is what I imagine is causing me to receive File not found errors. Thanks to pdb I was able to find this issue, but I am unsure how to continue. In all honesty, I am completely unsure if this problem is paramiko related or if it's some weird python behavior that I haven't encountered yet.
Also, sorry for no stack trace. I'll try to obtain one if possible, but I'm a bit pressed for time right this second.
ok so i have vulnserver.exe running on my win7 box waiting for input on port 9999. It takes in certain commands with parameters one of which is TRUN and is designed to trigger a buffer overflow if the TRUN parameters are the right length:
this is the python im running on kali linux to try to connect to vulnserver and see if can cause a crash:
import socket
numAs = 10
try:
while True:
# open a connection to vulnserver
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
s.connect (("194.168.1.154", 9999))
# receive the banner for vulnserver
s.recv (1024)
print "[*] Sending " + str(numAs) + " As"
# send the number of As to fuzz the HTER command
s.send ("HTER " + "A" * numAs + " \r\n")
# receive the response from vulnserver
s.recv (1024)
# close the connection
s.close ()
# increase the number of As we send next time
numAs += 10
except:
# if we get to here then something happened to vulnserver because the
connection is closed
print "Socket closed after sending " + str(numAs - 10) + " As"
however here is the command line output im getting
./hterfuzz.py: line 2: numAs: command not found
./hterfuzz.py: line 3: try:: command not found
./hterfuzz.py: line 6: syntax error near unexpected token `('
./hterfuzz.py: line 6: `s = socket.socket (socket.AF_INET,socket.SOCK_STREAM)'
Im very new to python and dont understand some basic errors so any help would be greatly appreciated. Thanks so much !
also the vulnserver.exe program is available here :
http://sites.google.com/site/lupingreycorner/vulnserver.zip
and the tutorial on fuzzing using vulnserver is here:
https://samsclass.info/127/proj/vuln-server.htm
if there is any other info I can provide just ask, Im simply trying to fix the errors in the py script so I can play around with it to try and find out whats needed to cause the overflow and eventually modify it to create a useful input string to execute processes on the win7 box by sending the string to vulnserver.
Thanks for any help people :)
Quite a simple one this - your script is being interpreted by bash, not python.
Just add this as the first line of your code: #!/usr/bin/python
I have written a paramiko script to batch-transfer files with sftp. The script works fine on my development machine -- Linux Mint 13, using Python 2.7.
When I moved the script to the production system, I found I had to build Python from scratch on it since the system Python was too old. So I built Python 2.7 on it --Centos -- and then attempted to run my script. It failed with a:
paramiko.SSHException - Errno 110, connection timeout
I've googled for that exception, but didn't find anything that seemed to fit. The script seems to 'hang' and the timeout on the paramiko.Transport((host, port)) part.
I thought this strange so attempted to do an sftp using openssh from that system, just to assure the remote host was responsive. It was -- and it worked.
So, now I go back to my script and simplify everything so it makes a bare-bones connection .. Still, I get a connection timeout. I don't know how to turn up debug with paramiko. Any suggestions?
Here's the basic script:
import os.path
import sys
import traceback
import paramiko
host = 'sftp.host.com'
user = 'user'
pw = 'password'
storepath = '/home/ftpservice/download'
is_dir = lambda x: oct(x)[1:3] == '40'
is_file = lambda x: oct(x)[1:3] == '10'
tp = paramiko.Transport((host, 22))
print 'tp is made, connecting '
tp.connect(username=user, password=pw, hostkey=None)
sftp = tp.open_sftp_client()
print 'sftp client made, now listing files'
filelist = sftp.listdir('.')
print filelist
for i in filelist:
fs = sftp.stat(i)
print "file is %s " % i
print "stmode %s" % sftp.stat(i).st_mode
if is_dir(sftp.stat(i).st_mode):
print "%s is a directory " % i
elif is_file(sftp.stat(i).st_mode):
print "%s is a file " % i
else:
print "no clue what %s is " % i