Multiple password attempts for Telnet connection - python

So I have the following code which establishes a Telnet connection to a virtual machine on my local machine:
from telnetlib import Telnet
try:
tnet = Telnet('127.0.0.1', 2282, 3)
except Exception as e:
print('Failed!')
# The connection has been established!
print('Success!')
for i in range(0,5):
tnet.read_until(b"Password: ")
tnet.write(b'password' + b'\r\n')
tnet.write(b'v' + b'\n\r')
tnet.close()
break
The connection succeeds, but I need to be able to access the machine from code! I will replace the 'password' with a user's attempt, but I can't tell if the attempt has even worked and if it hasn't then how can I retry another attempt?
**EDIT: **
I tested the Telnet connection from my terminal on the host machine and the terminal output is like this:
telnet 127.0.0.1 2282
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Password:
Login incorrect
admin1-VirtualBox login: admin1
Password:
So if I check first for read_until(b'Password: ') and it fails, should I catch it and create a loop containg more read_until statements? Or is there a much neater way to do this.
A previous way I thought about doing this was attempting a whole new telnet connection every time it was wrong in a while loop
Thanks!

Related

Is there any way to test the weblogic admin connecting URL (t3/t3s) before connecting to it

I'm using following command to connect to weblgic using WLST,
java weblogic.wlst core.py
inside core.py I'm calling following command to connect to the weblogic admin. but some times the service url becomes unresponsive And my script hangs occasionally due to this. Is there any way to give a timeout to this connect() method or any other method to implement a timeout functionality?. Appreciate if someone can shed some light on this. Thanks.
connect(username,password,t3://:)
in earlier WebLogic versions they have provided following functionality(to ping), but they have removed it after 12.2*
java weblogic.Admin -url t3://localhost:7001 -username weblogic -password weblog
ic ping 3 100
This is a very common situation, where you can use Python's socket module to check that the Admin port is opened or not with the following function.
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
AdminIP = '192.168.33.10'
result = sock.connect_ex((AdminIP,7001))
if result == 0:
print "AdminPort is open you can connect"
else:
print "Admin Port is not yet open"
sock.close()
add your logic accordingly, HTH!

Checking ip:port is open on remote host

I have a list of servers and ip:ports (external addressses) and i need to check if each server can connect to those addresses.
Looping through the file and trying to open an sshtunnel and doing connect as below
tunnel=sshtunnel.SSHTunnelForwarder(
ssh_host=host,
ssh_port=22,
ssh_username=ssh_username,
ssh_pkey=privkey,
remote_bind_address=(addr_ip, int(addr_port)),
local_bind_address=('0.0.0.0', 10022)
#,logger=sshtunnel.create_logger(loglevel=10)
)
tunnel.start()
# use socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
res = s.connect(('localhost', 10022))
print(res)
#s.connect((addr_ip, int(addr_port)))
s.close()
except socket.error as err:
print('socket err:')
print(err)
finally:
s.close()
time.sleep(2)
tunnel.stop()
When i do this though, the response is always 0 (i.e. the sock can connect to the local bind) even if the remote is incorrect - however sshtunnelforwarder throws
ERROR | Secsh channel 0 open FAILED: Network is unreachable: Connect failed
ERROR | Could not establish connection from ('127.0.0.1', 10022) to remote side of the tunnel
How do I make my socket command check if the remote_bind_address is available?
I tried to do use telnetlib, but get a similar issue
the code is effectively the same with the socket block replaced with
tn=telnetlib.Telnet()
tn.open('localhost',10022)
tn.close()
Im relatively new to all this, so still learning. If there is a better way to achieve what i need to do please let me know.
Thanks
Set the attribute skip_tunnel_checkup to False to enable checking of the remote side availability (it's disabled by default for backwards compatibility):
tunnel.skip_tunnel_checkup = False
Adding this before starting the tunnel checks the remote side is up on start and throws an exception which can be handled.
Removed my socket code.
I haven't tried that, but there's the tunnel_is_up attribute of the SSH tunnel class, which according to the documentation:
Describe whether or not the other side of the tunnel was reported to be up (and we must close it) or not (skip shutting down that tunnel)
Example of its content (it's a dictionary):
{('127.0.0.1', 55550): True, # this tunnel is up
('127.0.0.1', 55551): False} # this one isn't
So you shouldn't need to make an explicit connection yourself.
Note: you may need to set the attribute skip_tunnel_checkup to False (which is True by default for backwards compatibility) first before setting up the tunnel, otherwise tunnel_is_up may always report True:
When skip_tunnel_checkup is disabled or the local bind is a UNIX socket, the value will always be True
So the code may look like:
tunnel=sshtunnel.SSHTunnelForwarder(
# ...
)
tunnel.skip_tunnel_checkup = False
tunnel.start()
# tunnel.tunnel_is_up should be populated with actual tunnel status(es) now
In the code you posted, you're setting up a tunnel and then just opening a socket to the local endpoint of the tunnel, which is apparently open no matter what state the tunnel is in, so it always connects successfully.
Another approach would be to actually try to establish an SSH connection through the tunnel, but that's the paramiko.SSHclient alternative you're mentioning in a comment I guess.

FTP Connection/Instantiation Hangs Application

I am attempting to open a connection via FTP using the following simple code. But the code is just hanging at this line. Its not advancing, its not throwing any exceptions or errors. My code is 6 months old and I've been able to use this code to connect to my website and download files all this time. Today its just started to hang when I go to open a FTP connection.
Do you know what could be going wrong?
ftp = ftplib.FTP("www.mySite.com") # hangs on this line
print("Im alive") # Never get printed out
ftp.login(username, password)
I administer the website with a couple of other people but we haven't changed anything.
Edit: Just tried to FTP in using Filezilla with the same username and password and it failed. The output was:
Status: Resolving address of www.mySite.com
Status: Connecting to IPADDRESS...
Status: Connection established, waiting for welcome message...
Error: Connection timed out
Error: Could not connect to server
Status: Waiting to retry...
Status: Resolving address of www.mySite.com
Status: Connecting to IPADDRESS...
Status: Connection established, waiting for welcome message...
Error: Connection timed out
Error: Could not connect to server
Looks like you have server issues, but if you'd like the Python program to error out instead of waiting forever for the server, you can specify a timeout kwarg to ftplib.FTP. From the docs (https://docs.python.org/2/library/ftplib.html#ftplib.FTP)
class ftplib.FTP([host[, user[, passwd[, acct[, timeout]]]]])
Return a new instance of the FTP class. When host is given, the method call connect(host) is made. When user is given, additionally
the method call login(user, passwd, acct) is made (where passwd and
acct default to the empty string when not given). The optional timeout
parameter specifies a timeout in seconds for blocking operations like
the connection attempt (if is not specified, the global default
timeout setting will be used).
Changed in version 2.6: timeout was added.

Grab banner of different ports with python

I'm working on a script that grabs the banner from common ports of a host. I'm using sockets to make the connection but I'm facing some issues. Here is the code:
try:
connsocket = socket(AF_INET, SOCK_STREAM)
connsocket.settimeout( 5 )
connsocket.connect((ip, port))
connsocket.send("HEAD / HTTP/1.0")
results = connsocket.recv(400)
connsocket.close()
return str(results)
except:
print '[ERROR]Failed to connect or Connection timed out'
The are two major issues:
First time I run the script to a host all the banners are retrieved correctly except port 80 which exits with the timeout
The second problem is that when I relaunch the script to the same host there is no response from any port.
I suspect that the second issue is due to the connection is still open and the script fails retying to connect. With the first issue I have no idea why it's not working.
Any idea?
Regards.

connection refused from server unit I reset client machine

Below is the code I am running within a service. For the most part the script runs fine for days/weeks until the script hiccups and crashes. I am not so worried about the crashing part as I can resolve the cause from the error logs an patch appropriately. The issue I am facing is that sometimes when the service restarts and tries to connect to the server again, it gets a (10061, 'Connection refused') error, so that the service is unable to start up again. The bizarre part is that there is no python processes running when connections are being refused. IE no process with image name "pythonw.exe" or "pythonservice.exe." It should be noted that I am unable to connect to the server with any other machine as well until I reset computer which runs the client script. The client machine is running python 2.7 on a windows server 2003 OS. It should also be noted that the server is coded on a piece of hardware of which I do not have access to the code.
try:
EthernetConfig = ConfigParser()
EthernetConfig.read('Ethernet.conf')
HOST = EthernetConfig.get("TCP_SERVER", "HOST").strip()
PORT = EthernetConfig.getint("TCP_SERVER", "PORT")
lp = LineParser()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
reader = s.makefile("rb")
while(self.run == True):
line = reader.readline()
if line:
line = line.strip()
lp.parse(line)
except:
servicemanager.LogErrorMsg(traceback.format_exc()) # if error print it to event log
s.shutdown(2)
s.close()
os._exit(-1)
Connection refused is an error meaning that the program on the other side of the connection is not accepting your connection attempt. Most probably it hasn't noticed you crashing, and hasn't closed its connection.
What you can do is simply sleep a little while (30-60 seconds) and try again, and do this in a loop and hope the other end notices that the connection in broken so it can accept new connections again.
Turns out that Network Admin had the port closed that I was trying to connect to. It is open for one IP which belongs to the server. Problem is that the server has two network cards with two separate IP's. Issue is now resolved.

Categories