ssh-login with python.paramiko module into cisco device fails - python-2.7

I try to make a ssh-login into a cisco device, which fails with paramiko.SSHClient.
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
transport = ssh.get_transport()
ssh.connect(hostname, username='user', password='pwd')
ssh.close()
With paramiko.DEBU turned on:
DEBUG:paramiko.transport:starting thread (client mode): 0x2efdc18L
INFO:paramiko.transport:Connected (version 1.99, client Cisco-1.25)
DEBUG:paramiko.transport:kex algos:['diffie-hellman-group1-sha1'] server key:['ssh- rsa'] client encrypt:['aes128-cbc', '3des-cbc', 'aes192-cbc', 'aes256-cbc'] server encrypt:['aes128-cbc', '3des-cbc', 'aes192-cbc', 'aes256-cbc'] client mac:['hmac-sha1', 'hmac-sha1-96', 'hmac-md5', 'hmac-md5-96'] server mac:['hmac-sha1', 'hmac-sha1-96', 'hmac-md5', 'hmac-md5-96'] client compress:['none'] server compress:['none'] client lang:[''] server lang:[''] kex follows?False
DEBUG:paramiko.transport:Ciphers agreed: local=aes128-cbc, remote=aes128-cbc
DEBUG:paramiko.transport:using kex diffie-hellman-group1-sha1; server key type ssh-rsa; cipher: local aes128-cbc, remote aes128-cbc; mac: local hmac-sha1, remote hmac-sha1; compression: local none, remote none
DEBUG:paramiko.transport:Switch to new keys ...
DEBUG:paramiko.transport:Adding ssh-rsa host key for 172.20.112.77: ff666b2246321237c117d838f56df217
DEBUG:paramiko.transport:Trying discovered key 33e9714dae2cebdcfa3f30820ed2b17b in C:\Users\lauener/.ssh/id_rsa
DEBUG:paramiko.transport:userauth is OK
DEBUG:paramiko.transport:Authentication type (publickey) not permitted.
DEBUG:paramiko.transport:Allowed methods: ['keyboard-interactive', 'password']
INFO:paramiko.transport:Disconnect (code 2): Protocol error: expected packet type 50, got 5
I tried to do something with Transport but for
transport = ssh.get_transport()
transport is None.
But if I try to connect with the simple_demo provided by paramiko I can connect.
The following code works:
# get host key, if we know one
hostkeytype = None
hostkey = None
try:
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
except IOError:
try:
# try ~/ssh/ too, because windows can't have a folder named ~/.ssh/
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
except IOError:
print '*** Unable to open host keys file'
host_keys = {}
if host_keys.has_key(hostname):
hostkeytype = host_keys[hostname].keys()[0]
hostkey = host_keys[hostname][hostkeytype]
print 'Using host key of type %s' % hostkeytype
# now, connect and use paramiko Transport to negotiate SSH2 across the connection
try:
t = paramiko.Transport((hostname, port))
t.connect(username='user', password='pwd', hostkey=hostkey)
t.close()
except Exception, e:
print '*** Caught exception: %s: %s' % (e.__class__, e)
traceback.print_exc()
try:
t.close()
except:
pass
sys.exit(1)
But I think I would be more comfortable with using SSHClient. Thats why I would appreciate any help on this.
Thank you.

try setting the allow_agent and look_for_keys to false or else the ssh client will try to use your ssh agent if active or any ssh keys in the default path.
ssh.connect(hostname, username='user', password='pwd', allow_agent=False,look_for_keys=False)

Had the same issue, c0m4 answer resolved it :
>>> sshobj.connect('192.168.0.200', username=usr, password=pass, allow_agent=False,look_for_keys=False)
DEBUG:paramiko.transport:starting thread (client mode): 0x9ecfc4cL
INFO:paramiko.transport:Connected (version 2.0, client Cisco-1.25)
DEBUG:paramiko.transport:kex algos:['diffie-hellman-group-exchange-sha1', 'diffie-hellman-group14-sha1', 'diffie-hellman-group1-sha1'] server key:['ssh-rsa'] client encrypt:['aes128-cbc', '3des-cbc', 'aes192-cbc', 'aes256-cbc'] server encrypt:['aes128-cbc', '3des-cbc', 'aes192-cbc', 'aes256-cbc'] client mac:['hmac-sha1', 'hmac-sha1-96', 'hmac-md5', 'hmac-md5-96'] server mac:['hmac-sha1', 'hmac-sha1-96', 'hmac-md5', 'hmac-md5-96'] client compress:['none'] server compress:['none'] client lang:[''] server lang:[''] kex follows?False
DEBUG:paramiko.transport:Ciphers agreed: local=aes128-cbc, remote=aes128-cbc
DEBUG:paramiko.transport:using kex diffie-hellman-group1-sha1; server key type ssh-rsa; cipher: local aes128-cbc, remote aes128-cbc; mac: local hmac-sha1, remote hmac-sha1; compression: local none, remote none
DEBUG:paramiko.transport:Switch to new keys ...
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:**Authentication (password) successful!**
>>>

Related

How do I get the client Remote Port number in a Django?

I know I can use request.META['REMOTE_ADDR'] to get the client's IP in my django view function.
However, I have no idea how to get the client remote port number.
For example, you can see your own remote port number on the site below:
https://www.myip.com/
Remote Port
here is sample of view.py:
if request.user.is_authenticated:
        gelenIleti = request.META.get('HTTP_X_FORWARDED_FOR')
        if gelenIleti:
            ip = gelenIleti.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
            portNumarasi = request.META['SERVER_PORT']
        logger.info(' ' + 'LOG KAYDI :' + ' ' + ' KULLANICI : ' + request.user.username + ' ' + ' IP : ' + ip + ' ' + ' SERVER PORT : ' + portNumarasi)
You can get the IP and PORT through WSGIRequest connected socket.
Django 1.11:
sock = request._stream.stream._sock
client_ip, port = sock.getpeername()
Django 2.1:
sock = request._stream.stream.raw._sock
client_ip, port = sock.getpeername()
Django 2.2 and 3.1:
sock = request._stream.stream.stream.raw._sock
client_ip, port = sock.getpeername()
UPDATE
if request.user.is_authenticated:
sock = request._stream.stream.stream.raw._sock
client_ip, port = sock.getpeername()
logger.info(' LOG KAYDI : KULLANICI : %s IP : %s SERVER PORT : %s' % (request.user.username, client_ip, port))

I'm using mysql-connector-c++ 1.1.9 but I'd like to connect to the mysql db via socket not tcp

Does the library allow for connecting to the db via socket or do you have to use tcp and if so does anybody know the correct format?
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("/var/run/mysql/mysql.sock", "user1", "passphrase");
I just get a connection refused from the db
# ERR: Can't connect to MySQL server on '127.0.0.1' (111 "Connection refused") (MySQL error code: 2003, SQLState: HY000 )
According to the documentation the first argument to connect() should be in the form of a URL, and the unix: protocol is used to refer to a Unix-domain socket. So it should be:
con = driver->connect("unix:///var/run/mysql/mysql.sock", "user1", "passphrase");
I guess it defaults to tcp://127.0.0.1 when it can't parse the parameter.
Try with :
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("unix:///var/run/mysql/mysql.sock", "user1", "passphrase");
Check if the unix socket file is working.

Sending string via socket qpython3 android (client) to python2.7 linux (server)

Someone know how can I send string by socket qpython3 android (client) to python2.7 linux (server)?
For python2.7 linux (server) ok, I know, but I dont know how create the client with qpython3 android.
Someone Know?
TKS
My code for server in linux:
import socket
HOST = ''
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
orig = (HOST, PORT)
tcp.bind(orig)
tcp.listen(1)
while True:
con, client = tcp.accept()
print 'Connected by', client
while True:
msg = con.recv(1024)
if not msg: break
print cliente, msg
print 'Ending client connection', client
con.close()
For client in android:
import sl4a
import socket
HOST = '127.0.0.1'
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dest = (HOST, PORT)
tcp.connect(dest)
print 'Press x to close'
msg = droid.dialogGetInput('Text', 'Input value').result
while msg <> 'x':
tcp.send ((msg).encode('utf-8'))
msg = droid.dialogGetInput('Text', 'Input value').result
tcp.close()
But this send erro on android:
socket.error: [Errno 111] Connection refused
Do U know wats happening?
Tks
It's your loopback address this wont work
HOST = '127.0.0.1'
Instead that use true ip address on network for your host and make sure port of 5000 on server is open already

ESP8266 NodeMCU Lua "Socket client" to "Python Server" connection not possible

I was trying to connect a NodeMCU Socket client program to a Python server program, but I was not able to establish a connection.
I tested a simple Python client server code and it worked well.
Python Server Code
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
print c.recv(1024)
c.send('Thank you for connecting')
c.close() # Close the connection
Python client code (with this I tested the above code)
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
s.send('Hi i am aslam')
print s.recv(1024)
s.close # Close the socket when done
The output server side was
Got connection from ('192.168.99.1', 65385)
Hi i am aslam
NodeMCU code
--set wifi as station
print("Setting up WIFI...")
wifi.setmode(wifi.STATION)
--modify according your wireless router settings
wifi.sta.config("xxx", "xxx")
wifi.sta.connect()
function postThingSpeak()
print("hi")
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
srv:connect(12345, "192.168.0.104")
srv:on("connection", function(sck, c)
print("Wait for connection before sending.")
sck:send("hi how r u")
end)
end
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip() == nil then
print("Waiting for IP address...")
else
tmr.stop(1)
print("WiFi connection established, IP address: " .. wifi.sta.getip())
print("You have 3 seconds to abort")
print("Waiting...")
tmr.alarm(0, 3000, 0, postThingSpeak)
end
end)
But when I run the NodeMCU there is no response in the Python server.
The Output in the ESPlorer console looks like
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
WiFi connection established, IP address: 192.168.0.103
You have 3 seconds to abort
Waiting...
hi
Am I doing something wrong or missing some steps here?
Your guidance is appreciated.
After I revisited this for the second time it finally clicked. I must have scanned your Lua code too quickly the first time.
You need to set up all event handlers (srv:on) before you establish the connection. They may not fire otherwise - depending on how quickly the connection is established.
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
srv:on("connection", function(sck)
print("Wait for connection before sending.")
sck:send("hi how r u")
end)
srv:connect(12345,"192.168.0.104")
The example in our API documentation is wrong but it's already fixed in the dev branch.

Fabric does not use SSH key [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using an SSH keyfile with Fabric
In my fable
env.ip = 'x.x.x.x'
env.hosts = [env.ip]
env.user = 'root'
env.environment = 'production'
I have the config like this, but when I trying to execute something using run(command), it prompts me to put the password for root, why?
In my native Terminal.app, I can ssh x.x.x.x without entering the password.
I have enabled logging in the fabfile, and here is the ouput
DEBUG:ssh.transport:starting thread (client mode): 0xaa84dd0L
INFO:ssh.transport:Connected (version 2.0, client OpenSSH_5.8p1)
DEBUG:ssh.transport:kex algos:['ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521', 'diffie-hellman-group-exchange-sha256', 'diffie-hellman-group-exchange-sha1', 'diffie-hellman-group14-sha1', 'diffie-hellman-group1-sha1'] server key:['ssh-rsa', 'ssh-dss'] client encrypt:['aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'arcfour256', 'arcfour128', 'aes128-cbc', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'aes192-cbc', 'aes256-cbc', 'arcfour', 'rijndael-cbc#lysator.liu.se'] server encrypt:['aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'arcfour256', 'arcfour128', 'aes128-cbc', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'aes192-cbc', 'aes256-cbc', 'arcfour', 'rijndael-cbc#lysator.liu.se'] client mac:['hmac-md5', 'hmac-sha1', 'umac-64#openssh.com', 'hmac-ripemd160', 'hmac-ripemd160#openssh.com', 'hmac-sha1-96', 'hmac-md5-96'] server mac:['hmac-md5', 'hmac-sha1', 'umac-64#openssh.com', 'hmac-ripemd160', 'hmac-ripemd160#openssh.com', 'hmac-sha1-96', 'hmac-md5-96'] client compress:['none', 'zlib#openssh.com'] server compress:['none', 'zlib#openssh.com'] client lang:[''] server lang:[''] kex follows?False
DEBUG:ssh.transport:Ciphers agreed: local=aes128-ctr, remote=aes128-ctr
DEBUG:ssh.transport:using kex diffie-hellman-group1-sha1; server key type ssh-rsa; cipher: local aes128-ctr, remote aes128-ctr; mac: local hmac-sha1, remote hmac-sha1; compression: local none, remote none
DEBUG:ssh.transport:Switch to new keys ... [x.x.x.x] Login password for 'root':
You have to specify the path to the keyfile to use.
See this post for details, which boil down to adding
env.key_filename = '/path/to/keyfile.pem'
in your case.