I am trying to make a script, which connects to a server by telnet. I am using python and telnetlib. I have problems getting timeout to work. I want to use the optional timeout when connecting to host, so that I get an exception if the host isn't online.
I have read the python telnetlib documentation but I have no idea what's wrong with my code.
Here is my simple code:
import telnetlib
host = 'hostname'
tn = telnetlib.Telnet(host, 23, 5) # port 23, timeout 45secs
print 'Connecting to', host
tn.close()
And here is my error message:
Exception exceptions.AttributeError: "Telnet instance has no attribute 'sock'" in <bound method Telnet.__del__ of <telnetlib.Telnet instance at 0x7f269864b8c0>> ignored
Traceback (most recent call last):
File "test2.py", line 7, in <module>
tn = telnetlib.Telnet(host, 23, 5)
TypeError: __init__() takes at most 3 arguments (4 given)
You probably aren't using python 2.6 or above. Quote from the docs:
Changed in version 2.6: timeout was added.
Related
I wanted to connect to a server, but it gave me an error that I need a method of SSH athentication, so I simply made a key-value pair with "open()" and "connect_kwargs".
As I specified earlier this is my code:
from fabric import Connection
import socket
uinaaaa = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
uinaaaa.connect(("8.8.8.8", 80))
xin = uinaaaa.getsockname()[0]
PERSONA = Connection(f"user#{xin}")
PERSONA.open(connect_kwargs={'password': "LOSER"})
print("Ok, now you will learn all the server's commands!")
YUIA = PERSONA.run("help")
print(YUIA.standout)
print("If you want to learn more, type man, after that, a space, and then the command to learn more!")
but I got:
Traceback (most recent call last):
File "main.py", line 7, in <module>
PERSONA.open(connect_kwargs={'password': "LOSER"})
TypeError: open() got an unexpected keyword argument 'connect_kwargs'
I don't know how to fix this. Is it an entirely differnet function then "open()" or just a different argument than connect_kwargs? Please help!
I'm trying to loop through some PDU servers to check entries are following our naming conventions.
I'm writing a python script to check all these servers. However, I'm running into a problem where if the server is down, it makes my script error out and fail.
I don't know how to deal with the gaierror I'm getting on some servers that are unreachable or non-existent. I thought I handled it in the "finally" block but apparently not.
Here's my code.
try:
tn = telnetlib.Telnet()
tn.open(pdu_host)
print(tn.read_until(b'Username: '))
tn.write(PDU_USER + b"\n")
print(tn.read_until(b'Password: '))
tn.write(PDU_PASSWORD + b"\n")
_, _, data = tn.expect([br'Switched .DU:'])
finally:
# close the connection
if tn is not None:
tn.write(b'logout\n')
print(tn.read_all())
tn.close()
print ('logged out')
time.sleep(2) # give the connection time to close
It seems like when I get a gaierror, tn is not None and still tries to run the commands in the finally block, which makes my script fail. When I manually try to telnet to the server, it says:
could not resolve serverX/telnet: Name or service not known
How do I handle this error case when my existing code didn't handle it?
EDIT: This is the error I'm getting when running my script.
Traceback (most recent call last):
File "check_pdu_outlets.py", line 58, in <module>
tn.write(b'logout\n')
File "/usr/lib/python2.7/telnetlib.py", line 283, in write
self.sock.sendall(buffer)
AttributeError: 'NoneType' object has no attribute 'sendall'
When I run the script thru pdb and I step through the code line by line, it says I get the gaierror when it tries to open a non-existent or down server
-> tn.open(pdu_host)
(Pdb) n
gaierror: (-2, 'Name or service not known')
A simple way to resolve this is to change your if statement in finally() to check if an open socket exists for the connection.
if tn.get_socket():
If no connection is open, it will return None
Example
from telnetlib import Telnet
tn = Telnet()
print(type(tn.get_socket()))
#<class 'NoneType'>
tn.open('192.168.0.1')
tn.get_socket()
#<socket.socket fd=764, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('192.168.1.1', 54489), raddr=('192.168.0.1', 23)>
tn.close()
print(type(tn.get_socket()))
#<class 'NoneType'>
From telnetlib.py:
def get_socket(self):
"""Return the socket object used internally."""
return self.sock
I'm facing the following problem.
I'm using pydbus python package to test API by connecting to a target linux machine which is in the same network by using the environment variable DBUS_SYSTEM_BUS_ADDRESS
Under normal circumstances this works well, I'm able to call any valid API over the proxy object created.
Eg:
import os
import pydbus
os.environ['DBUS_SYSTEM_BUS_ADDRESS'] = \
"tcp:host=192.168.1.100,port=55556,family=ipv4"
bus = pydbus.SystemBus()
proxy = bus.get("busname", "object_path")
return_value = proxy.method-name(args)
As part of my testing, my target linux machine gets rebooted in between and when I re-use the proxy object, I get the following error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/harman/.local/lib/python2.7/site-packages/pydbus/proxy.py", line 47, in get
0, timeout_to_glib(timeout), None)
GLib.Error: g-io-error-quark: The connection is closed (18)
I realize that the previous connection no longer exists, so I tried re-initialising the connection with the following
bus = pydbus.SystemBus()
proxy = bus.get("busname", "object_path")
I get the same error on the bus.get() statement.
Is there a solution/possible workaround to this problem?
I'm creating an extremely simple python script designed to open a TCP socket and send some JSON data. (I'm new to python)
I'm recieving an error below when I run the script:
Traceback (most recent call last):
File "JSONTest.py", line 17, in <module>
s.connect('10.12.0.30', 6634)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
TypeError: connect() takes exactly one argument (2 given)
My script is below:
#Imports
import socket
import json
import time
data = "{\"method\": \"echo\",\"id\": \"echo\",\"params\": []}"
#Create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Establish TCP session via IP address and port specified
s.connect('10.12.0.30', 6634)
#Send JSON to socket
s.send(json.dumps(data))
#Wait for response and print to console
result = json.loads(s.recv(1024))
#print str(result)
#Exit
s.close()
I've checked the documentation on the socket library and connect() lists only a single argument, namely the destination IP address desired. So, my question is, how can I do the above, where I'm also specifying my TCP port, if the connect() method won't allow me to input it there?
I'm also open to input on better ways to accomplish this.
Host and port must be a tuple.
s.connect(('10.12.0.30', 6634))
See the second part of the example in the Python Socket documentation here.
You must call connect with one argument: a tuple with the host and the port:
s.connect(('10.12.0.30',6677))
Check this solution using socket.getaddrinfo:
ainfo = socket.getaddrinfo("10.12.0.30",6677)
s.connect(ainfo[0][4])
You should check the version of the python because socket.connect(.....) takes tuple after version 2.0 and later, please follow the python documentation for that version here is the snip of the documentation for python 2.7:
socket.connect(address)
Connect to a remote socket at address. (The format of address depends
on the address family — see above.)
Note This method has historically accepted a pair of parameters for
AF_INET addresses instead of only a tuple. This was never intentional
and is no longer available in Python 2.0 and later.
While browsing about changing identity with tor I have the following script:
from TorCtl import TorCtl
conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="123")
TorCtl.Connection.send_signal(conn, "NEWNYM")
But I get this error:
Connection refused. Is the ControlPort enabled?
Traceback (most recent call last):
File "python_tor.py", line 18, in <module>
TorCtl.Connection.send_signal(conn, "NEWNYM")
TypeError: unbound method send_signal() must be called with Connection instance as first argument (got NoneType instance instead)
And What shoul be the passphrase? I have tried without passphrase the same error occurs.
I think you should do
conn.send_signal("NEWNYM")
You could try printing conn in between the calls. See if it's None. Maybe the connection failed.
Look at vivaldia settings, in the advanced tab, look at the address and the port number below controlport, it may be 9151 instead of 9050. Then set another password (uncheck the box random password).