I am trying to make the Python Telnetlib to work with a PDU41001 switched power bar. I previously tried to interact with the device via putty using telnet and it works fine.
In my code, I'm able to connect to the device successfully as the code raise an exception if I change the IP address or the port, but there doesn't seem to be any output from the device whatsoever. Sending carriage returns doesn't seem to change anything. I'm out of ideas and I have no idea if it is an issue with the device, with the lib or with my code.
Here's the function I'm using to connect to the device. I tried to add delays to test if there was an issue with timing but it doesn't seem to change anything. I'm using VSCode to debug and validate input data from the device.
def connect(self):
"""
Establish a telnet connection with credentials
"""
self.ping_ip_address(self.connection["host"])
self.telnet_socket = telnetlib.Telnet()
self.telnet_socket.open(host=self.connection["host"], port=self.connection["port"])
time.sleep(1)
response = self.telnet_socket.read_until('Login Name: ', timeout=2)
self.telnet_socket.write(self.credentials["user"] + "\r")
time.sleep(1)
response = self.telnet_socket.read_until('Login Password: ', timeout=2)
self.telnet_socket.write(self.credentials["password"] + "\r")
response = self.telnet_socket.read_until('Welcome Administrator!', timeout=TELNET_RESPONSE_TIMEOUT)
Related
I am attempting to communicate with a BraggMETER Interrogator that supports SCPI.
OS: Windows 10
Connection hardware: j5create JUH470 USB 3.0 Multi-Adapter Gigabit Ethernet / 3-Port USB 3.0 HUB
Part of my confusion: Should I access as a USB device or as a TCPIP device?
When I connect via Telnet, all goes well. The IP Address and Port are 10.0.0.10 and 3500.
> telnet
> open 10.0.0.10 3500
:IDEN?
:ACK:HBM FiberSensing:FS22SI v3.0:08:046 840 200 898:20190116
:STAT?
:ACK:1
In Python, I am usig the pyvisa library.
import easy_scpi as scpi
import pyvisa
DeviceAddress = '10.0.0.10'
DevicePort = '3500'
VISADevice = f'TCPIP0::{DeviceAddress}::{DevicePort}::SOCKET'
# Doesn't work either --> VISADevice = 'ASRL10::INSTR'
rm = pyvisa.ResourceManager()
print(rm.list_resources())
inst = rm.open_resource(VISADevice)
print(inst.query("*IDEN?"))
inst.close()
The error is always on rm.open_resource. I have tried numerous connection strings. They give different errors. Here are three of them:
pyvisa.errors.VisaIOError: VI_ERROR_INTF_NUM_NCONFIG (-1073807195): The interface type is valid but the specified interface number is not configured.
pyvisa.errors.VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.
pyvisa.errors.VisaIOError: VI_ERROR_RSRC_NFOUND (-1073807343): Insufficient location information or the requested device or resource is not present in the system.
Update 1
I downloaded National Instruments NI-Max and used their NI I/O trace. This connection string "works":
TCPIP::10.0.0.10::3500::SOCKET
However, I still get the timeout error. Tried ensuring that the newline termination character is sent and upped the timeout to 5 seconds (which did take effect, as it delayed the logging of the timeout error). No dice. Still gives a timeout error.
Update 2
While not the same setup, someone else reports a problem who is using an NI GPIB-to-USB card (GPIB-USB-HS). The common thread is a USB adapter...
https://community.keysight.com/thread/37567
I'm not able to comment so I'm commenting here
Have you tried using a normal socket?
import socket
DeviceAddress = '10.0.0.10'
DevicePort = '3500'
BUFSIZ = 1024
ADDR = (DeviceAddress, DevicePort)
cmd = "IDN?" # or "*IDEN?" as you've put?
braggMeterSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
braggMeterSocket.connect(self.ADDR)
braggMeterSocket.send(cmd + "\n") #maybe with new line depending on what the device terminator is.
mesg = braggMeterSocket.recv(BUFSIZ)
mesg = mesg.strip() # Remove \n at end of mesg
print(mesg)
The problem was that the device exects CRLF (carriage return plus linefeed) as an SCPI command terminator. I was only sending one of those two characters, "\n".
Python I/O does not adapt to the OS like some languages I have used, which will interpret "\n" as "\r\n" in some situations.
Likewise, NI-Max only sent the "\n" and omitted the "\r".
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")
Right now, I'm connecting to the ftp in bash using
echo "
user $USER1 $PASS1
user $USER2 $PASS2
user $USER3 $PASS3"|ftp -n $FTPSERVER
I tried to handle this in python using
ftp = ftplib.FTP(SERVER)
ftp.sendcmd("user {} {}".format(USER1, PASS1))
ftp.sendcmd("user {} {}".format(USER2, PASS2))
...
When I connect using bash, the output is
However, when I try using python, the first line only gives output "331 Password: " and if I send anymore commands, it gives the error Please supply password with PASS command.
Also, I'm not sure if it's relevant but $USER2 and $PASS2 have # in them with $PASS2 beginning with it.
I am trying to ssh to a test cisco router in a test environment using python paramiko, and run cisco commands in that test router.
Everything works great except for 1 small detail.
After running the script I want the ssh session to remain open. (so I can run other commands manually).
I want to keep the ssh session open until I type "exit"
I found another link with a similar issue but I cant understand the solution.
(See here Python ssh - keep connection open after script terminates)
I would appreciate if someone can help me out here
My code
import paramiko
import time
def ssh_session(ip):
try:
session = paramiko.SSHClient() #Open the session
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
session.connect(ip, username = "ciscouser1", password = "password")
connection = session.invoke_shell()
####Running Cisco IOS commands###
connection.send("enable\n")
connection.send("password1") #sending
connection.send("\n")
connection.send("configure terminal\n\n")
time.sleep(1)
connection.send("do show ip int brief\n")
time.sleep(1)
except paramiko.AuthenticationException:
print "wrong credentials"
ssh_session("10.10.10.1")
The session timeout would be controlled by the SSH server. To the best of my knowledge, the only way to keep your session alive on the client side is to not be inactive, which can be accomplished by sending null packets. As to how to do this specifically with paramiko I am not certain. Perhaps you could send some kind of dummy command (or maybe even an empty string?) every so often?
My Python application connects to a MSSQL database to verify some matter numbers, but this step is only necessary to assist with data integrity and does not bring the user any additional functionality.
The database is only accessible when on my office's local network. How do I check a user's environment during startup to see if this connection can be made?
I'm using pyodbc, but I also need this program to work on OS X, so I'm not importing that module until this check returns a positive result. Any ideas?
You could try something like this:
#!/usr/bin/python
import socket
mssql_server = 'foobar.example.not' # set this to your own value
s = socket.socket()
s.settimeout(3)
try:
server = [x for x in socket.getaddrinfo(mssql_server,1433) if x[0]==2 ][0][-1]
except socket.gaierror:
server = None
if server:
try:
s.connect(server)
except (socket.timeout, socket.error):
server = None
s.close()
... this should attempt to find an IPv4 address for your server (using the first one returned by getaddrinfo()) and then attempt to connect to the MS SQL TCP port (1433 by default) on that system. (Yes, change 1433 if your server is on a different port). If there's a timeout or any other socket error reported on the attempt, then server is set to None. Otherwise you probably have an MS SQL server that you could access.
Verify the host is available using ping before import:
import subprocess
host = "<hostname>"
# add sample text for ping resolution errors here
errors = ("could not find", "unreachable")
ping = "ping {0}".format(host)
(stdout, stderr) = subprocess.Popen(ping, stdout=subprocess.PIPE).communicate()
# stdout is a byte string and must be decoded before compare
if not any(error in stdout.decode("utf-8") for error in errors):
import pyodbc
.....