Python network programming - python

I read "python network programming" and got to learn about netmiko. I tried connecting to the Cisco network given in the book and it did not connect. I went online and read other articles on netmiko and tried their Examples using the router login details given in the book, but none of them worked. My internet connection is good (I checked it). Please what is wrong? Is it my location (I stay in Nigeria)?
The error given to me is as follows:
possible reasons why a connection cannot be established are as follows:
*Wrong hostname
*Wrong TCP/IP port
*Wrong password
*Blocked access to router
Please what is wrong, I need help. Or if you have any free router I can connect to just for the sake of learning I would like to know.

If you don't have direct ssh permission and you want to connect through a private server, you can also try paramiko instead of netmiko. Below I wrote an example of connecting via a server and entering the device by typing a command.
import paramiko
import time
from termcolor import colored
from timeit import default_timer as timer
import sys
global password
username = "ldap"
password = "pwd"
def vrf_implement_control(device_ip):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
remote_connection = ssh.connect(device_ip, port="2222", username=username, password=password, timeout=15)
remote_connection = ssh.invoke_shell()
# device_connection
remote_connection.send(" 192.168.0.10\n")
time.sleep(2)
print (colored ("connected_ip_address_"+ device_ip,"blue"))
except Exception as e:
print("erisim yok_\n")

I don't know which sample script you are trying. But as per your error, it looks like there is an issue with device connectivity, You can try to ping the device and check ssh is enabled or not.
Try to run the below script with your credentials, It should work.
from netmiko import ConnectHandler
cisco = {
'device_type': 'cisco_ios', #refer netmiko device type
'host': '10.10.1.1', #Replace with your device ip
'username': 'admin', #Router username
'password': 'cisco123', #password
}
net_connect = ConnectHandler(**cisco)
output = net_connect.send_command("show version")
print(output)

Related

Try to get client's computername in Django

I want to get the client's computername and computer login user in my django project in the intranet. So I use wmi with the ip to get that infomation. However some ip could not be connected by wmi, and come up with an error called "The RPC Server is unavailable". Then I try to use the computername to connect by wmi for testing, it worked. What causes this problem? I have used socket.getnamebyaddr also get the wrong computername.
'''
import wmi
ip = request.META.get('REMOTE_ADDR')
try:
conn = wmi.WMI(computer = ip,user = 'xx', password="xx")
for each in conn.Win32_ComputerSystem():
content = {
'user':json.dumps(each.UserName),
'comname':json.dumps(each.Name),
}
print(each.Name)
print(each.UserName)
'''
Use socket module instead of wmi.
import socket
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
More information can be found here

How to execute remote commands via SSH through authenticated HTTP Proxy?

I am posting the question and the answer, I found, as well, incase it would help someone. The following were my minimum requirements:
1. Client machine is Windows 10 and remote server is Linux
2. Connect to remote server via SSH through HTTP Proxy
3. HTTP Proxy uses Basic Authentication
4. Run commands on remote server and display output
The purpose of the script was to login to the remote server, run a bash script (check.sh) present on the server and display the result. The Bash script simply runs a list of commands displaying the overall health of the server.
There have been numerous discussions, here, on how to implement HTTP Proxy or running remote commands using Paramiko. However, I could not find the combination of both.
from urllib.parse import urlparse
from http.client import HTTPConnection
import paramiko
from base64 import b64encode
# host details
host = "remote-server-IP"
port = 22
# proxy connection & socket definition
proxy_url = "http://uname001:passw0rd123#HTTP-proxy-server-IP:proxy-port"
url = urlparse(proxy_url)
http_con = HTTPConnection(url.hostname, url.port)
auth = b64encode(bytes(url.username + ':' + url.password,"utf-8")).decode("ascii")
headers = { 'Proxy-Authorization' : 'Basic %s' % auth }
http_con.set_tunnel(host, port, headers)
http_con.connect()
sock = http_con.sock
# ssh connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname=host, port=port, username='remote-server-uname', password='remote-server-pwd', sock=sock)
except paramiko.SSHException:
print("Connection Failed")
quit()
stdin,stdout,stderr = ssh.exec_command("./check")
for line in stdout.readlines():
print(line.strip())
ssh.close()
I would welcome any suggestions to the code as I am a network analyst and not a coder but keen to learn and improve.
I do not think that your proxy code is correct.
For a working proxy code, see How to ssh over http proxy in Python?, particularly the answer by #tintin.
As it seems that you need to authenticate to the proxy, after the CONNECT command, add a Proxy-Authorization header like:
Proxy-Authorization: Basic <credentials>
where the <credentials> is base-64 encoded string username:password.
cmd_connect = "CONNECT {}:{} HTTP/1.1\r\nProxy-Authorization: Basic <credentials>\r\n\r\n".format(*target)

What is the minimum amount of information needed to access a SSH server using twisted.conch?

I'm a little over my head when it comes to this SSH thing. Basically I am trying to access a friends server through and SSH tunnel using twisted conch. He has given me the following information:
MONGO_HOST = "ip address"
MONGO_DB = "server name"
MONGO_USER = "user name"
MONGO_PASS = "server password"
I was able to get this information to work using the python library motor.motor_asyncio (I need this be async compatible in order to use with other libraries) but for reasons that I can get into if necessary, will not work on the raspberry pi that I plan on running this program on.
Long story short, I was wondering if anyone could help me with some sample code to access my friends server using the information given above with twisted.conch.
I looked on the twisted.conch readthedocs, but the example needs more information than I can provide (I think) and is WAY over my head in terms of networking/SSH/etc.
Thanks in advance. I am willing to put in the work, but I need to know where to look.
Here is my relevant bit of code so far:
from motor.motor_asyncio import AsyncIOMotorClient
from sshtunnel import SSHTunnelForwarder
MONGO_HOST = "host address"
MONGO_DB = "server name"
MONGO_USER = "username"
MONGO_PASS = "password"
server = SSHTunnelForwarder(
MONGO_HOST,
ssh_username=MONGO_USER,
ssh_password=MONGO_PASS,
remote_bind_address=('address', gate),
local_bind_address=('address', gate)
)
server.start()
client = AsyncIOMotorClient('address', gate)
db = client.server_name
You can forward ports with Conch like this:
rom twisted.internet.defer import Deferred
from twisted.conch.scripts import conch
from twisted.conch.scripts.conch import ClientOptions, SSHConnection
from twisted.conch.client.direct import connect
from twisted.conch.client.default import SSHUserAuthClient, verifyHostKey
from twisted.internet.task import react
def main(reactor):
# authenticate as this user to SSH
user = "sshusername"
# the SSH server address
host = "127.0.0.1"
# the SSH server port number
port = 22
# a local port number to listen on and forward
localListenPort = 12345
# an address to forward to from the remote system
remoteForwardHost = "127.0.0.1"
# and the port number to forward to
remoteForwardPort = 22
conch.options = ClientOptions()
conch.options.parseOptions([
# don't ask the server for a shell
"--noshell",
# set up the local port forward
"--localforward={}:{}:{}".format(
localListenPort,
remoteForwardHost,
remoteForwardPort,
),
# specify the hostname for host key checking
host,
])
# don't stop when the last forwarded connection stops
conch.stopConnection = lambda: None
# do normal-ish authentication - agent, keys, passwords
userAuthObj = SSHUserAuthClient(user, conch.options, SSHConnection())
# create a Deferred that will tell `react` when to stop the reactor
runningIndefinitely = Deferred()
# establish the connection
connecting = connect(
host,
port,
conch.options,
verifyHostKey,
userAuthObj,
)
# only forward errors so the reactor will run forever unless the
# connection attempt fails. note this does not set up reconnection for a
# connection that succeeds and then fails later.
connecting.addErrback(runningIndefinitely.errback)
return runningIndefinitely
# run the reactor, call the main function with it, passing no other args
react(main, [])
Some of the APIs are weird because they are CLI focused. You don't have to do it this way but port forwarding is most easily accessible with these APIs rather than the APIs that are more focused on programmatic use.

Python SFTP Bloomberg Data License - Paramiko

Is anybody aware of a Python solution to sftp into the Bloomberg enterprise service. We're converting some bloomberg pulling from Mathworks to Python. Historically, I would have done this in Mathworks like this using the bdl function.
username = 'xxxxx';
password = 'xxxxxxxx';
hostname = 'dlsftp.bloomberg.com';
portnumber = 30206;
decrypt = 'nAcLeZ';
c = bdl(username,password,hostname,portnumber,decrypt)
Any thoughts? Thanks!
OK, for anybody that needs SOCKS proxy through Bloomberg, here is what I've done and it works:
After some research, it appears the decrypt is not necessary. This code works, just be sure to include the two files for a test: ('readme.txt','readme-test.txt') on your bloomberg server using RequestBuilder or WinSCP.
# coding: utf-8
import paramiko
import socket
import socks
proxy_details = {'host': "xxx",
'port': 1080,
'username': "xxx",
'password': "xxx"}
auth_credentials = {'host': "sftp.bloomberg.com",
'username': "dlxxxxxx",
'password': "xxxxxx"}
s = socks.socksocket()
s.set_proxy(
proxy_type=socks.SOCKS5,
addr=proxy_details['host'],
port=proxy_details['port'],
username=proxy_details['username'],
password=proxy_details['password']
)
#setup the SFTP client using the connected socket
s.connect((auth_credentials['host'],22))
transport = paramiko.Transport(s)
transport.connect(username=auth_credentials['username'],
password=auth_credentials['password'])
# start SFTP Client from SSH transport
sftp = paramiko.SFTPClient.from_transport(transport) #.get_transport() was appended
#will download readme.txt from the remote server, and save as the filename in the second argument
sftp.get('readme.txt','readme-test.txt')
#Test whether transport is authenticated
print (transport.is_authenticated())
# cleanup
sftp.close()
transport.close()

ssh connection to a router with a python script

I wanted to know whether there is a possibility to use a python script in order to connect to a router and control the interface (shut down, restart wireless network etc..) with an ssh connection.
SO far I wrote these lines,but still it does not work. When i look to the terminal I see that everything is blocked at the point when my script should echo the password for the router to finalize the connection. How can I correct this please ?
Here are the lines :
import os, urllib, urllib2, re
def InterfaceControl():
#os.system("echo training")
os.system("ssh -l root 192.168.2.1")
os.system("echo yes")
os.system("echo My_ROUTER_PASSWORD")
os.system("shutdown -r")
def main():
InterfaceControl()
if __name__=="__main__":
main()
Thank you so much in advance
You can use paramiko which is a python library that abstracts remote shell connections through ssh with several options allowing users to use authentication with rsa keys, etc. This is a sample code you can reuse to solve your problem:
import paramiko
ssh = paramiko.SSHClient()
ssh.connect( 'hostname', username = 'username', password = 'password' )
ssh.exec_command( 'ls -al' )
By the way paramiko can be easily added to your python environment if you're running your script from a virtual environment (virtualenv).
plumbum is what you're looking for. (remote commands)

Categories