Using Paramiko I am trying to establish a connection with a server, but that connection is failing with the following output
Traceback (most recent call last):
File "C:\ucatsScripts\cleanUcatsV2.py", line 13, in <module>
ssh.connect(host,username,password)
File "C:\Python27\lib\site-packages\paramiko-1.7.6-py2.7.egg\paramiko\client.py", line 278, in connect
for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
socket.gaierror: [Errno 10109] getaddrinfo failed
Here is the code I am using
import paramiko
import cmd
import sys
# Connect to Server
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
success = ssh.connect('MASKED',username='MASKED',password='MASKED')
if (success != True):
print "Connection Error"
sys.exit()
else:
print "Connection Established"
any ideas?
Just add the port after the host and you'll be set:
ssh.connect('MASKED', 22, username='MASKED',password='MASKED')
BTW, as robots.jpg said, the connect method doesn't return anything. Instead of returning values it triggers exceptions.
Here is a more complete example:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paramiko, os, string, pprint, socket, traceback, sys
time_out = 20 # Number of seconds for timeout
port = 22
pp = pprint.PrettyPrinter(indent=2)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
file = open( "file.txt", "r" )
# NOTE: The file contains:
# host user current_password
array = []
for line in file:
array = string.split(line.rstrip('\n'),)
# pp.pprint(array)
try:
ssh.connect(array[0], port, array[1], array[2], timeout=time_out)
print "Success!! -- Server: ", array[0], " Us: ", array[1]
except paramiko.AuthenticationException:
print "Authentication problem -- Server: ", array[0], " User: ", array[1]
continue
except socket.error, e:
print "Comunication problem -- Server: ", array[0], " User: ", array[1]
continue
ssh.close()
file.close()
The code needs some polish but it does the job.
Be care to didn't have the username on your hostname
ssh.connect(hostname='user#example.com', port=22)
user#example.com isn't a hostname parameter that fit for the connection.
You should use:
ssh.connect(hostname='example.com', port=22, username='user')
Are you sure the hostname resolves to IP address? Try ping that_hostname on your machine to see.
You need to make some changes for DNS.
Go to Network Connections -> IPv4-> Advanced Settings -> DNS then check Append these DNS suffixes, and enter your machine dns.
This worked for me. Anyway this error comes from the Ethernet settings.
Good Luck !
Related
I have written a client-server python program where the client can send the data to the server. But when the client is trying to connect with the server I am getting the following error.
[Errno 110] Connection timed out
Sending Key to Server
Traceback (most recent call last):
File "client.py", line 43, in <module>
s.send(str(id))
socket.error: [Errno 32] Broken pipe
I tried the following solutions
Broken Pipe error and How to prevent Broken pipe error but none of them solved the issue.
Here are my client and server code
client.py
import socket
import os
import subprocess
from optparse import OptionParser
from random import randint
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket has been successfully created"
except socket.error as err:
print "socket creation failed with error %s" %(err)
# The Manager Address and port
host_ip='192.168.43.123'
port =10106
# Generates a random number say xxxx then its client id becomes 'clxxxx' and home directory made at the server as '/home/clxxxx' with permissions 700
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
id=random_with_N_digits(4)
id="cl"+ str(id)
# Looks for a public key in .ssh folder if temp.pub not present. If not found generates a ssh public private key and sends it to manager which then copies it to the server
subprocess.call(["bash","keygen.sh"])
#s = socket.socket()
try:
s.connect((host_ip,port))
print "the socket has successfully connected to Backup Server IP == %s" %(host_ip)
except socket.error as err:
print err
f = open('temp.pub','r')
print "Sending Key to Server"
j = "-"
s.send(str(id))
l=f.read(8192)
while(l):
print 'Sending...'
s.send(l)
l = f.read(8192)
try:
client_id=s.recv(1024)
data=s.recv(12)
ip=s.recv(24)
print client_id,
print data, ip
except:
print "An Unknown Error Occurred!"
f.close()
# Writes the parameters of client in the file 'backup_dir.txt'
with open('backup_dir.txt','w') as the_file:
the_file.write(client_id)
the_file.write('\n')
the_file.write(data)
the_file.write('\n')
the_file.write(ip)
the_file.write('\n')
f.close()
s.close()
server.py
import socket
import subprocess
import os
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket has been successfully created"
except socket.error as err:
print "socket creation failed with error %s" %(err)
port = 10106
s.bind(('', port))
print("socket binded to %s port" %port)
s.listen(10)
print("socket is listening")
while(True):
print("waiting for a connection")
c, addr = s.accept()
print("Got a connection from", addr,c)
clientID =(c.recv(8192))
key =(c.recv(8192))
print clientID
print key
with open("temp.pub", 'w') as fp:
fp.write(key)
note=subprocess.check_output("./test_user.sh "+ clientID, shell=True)
note = str(note)
print(len(note))
flag, path, serverIP = note.split(":")
print(flag)
print(path)
print(serverIP)
if flag:
c.send(clientID)
c.send(path)
c.send(serverIP)
os.remove("temp.pub")
else:
c.send("Unable to add Client.")
How do I fix this problem so that the client can send the data to the server without any error?
Thank You in advance.
The error resolved.
It was due to the firewall issue as #RaymondNijland was mentioning, Thanks.
I added the rule in the firewall to allow the following port for Socket Connection and it worked.
sudo ufw allow 10106
I an trying to use Paramiko with SOCKS proxy (SecureCRT or PuTTY configured as SOCKS proxy). I am using the below code
import paramiko,socks
host, port = '127.0.0.1', 1080
# Set up your proxy information for this socket
sock=socks.socksocket()
sock.set_proxy(
proxy_type=socks.SOCKS4,
addr=host,
port=port,
)
# Connect the socket
sock.connect((host, port))
# Create your Paramiko Transport
transport = paramiko.Transport(sock)
transport.connect(
username='username', #<------not sure if it is needed, the socks proxy needs no username/password
password='secret',
)
client = paramiko.client.SSHClient.connect('remotedevice', username='usernameonremotedevice',sock=sock)
stdin, stdout, stderr=client.exec_command("ls -la")
# Do stuff
# Clean up
client.close()
transport.close()
The above approach seems to confuse Paramiko since it is using 127.0.0.1 for both.
My issue originated in the Paramiko libraries used by Exscript so I wanted to simplify to see if this would work ....
This is the log that SecureCRT shows with each attempt
[LOCAL] : Starting port forward from 127.0.0.1 on local 127.0.0.1:1080 to remote 127.0.0.1:1080.
[LOCAL] : Could not start port forwarding from local service 127.0.0.1:3106 to 127.0.0.1:1080. Reason: The channel could not be opened because the connection failed. Server error details: Connection refused
The script fails like below:
Traceback (most recent call last):
File "C:\Users\Username\Documents\Eclipse\ESNetworkDiscovery\ParamikoProxyTest.py", line 24, in <module>
sock.connect((host, port))
File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\socks.py", line 96, in wrapper
return function(*args, **kwargs)
File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\socks.py", line 813, in connect
negotiate(self, dest_addr, dest_port)
File "C:\Utils\WPy2.7-32\python-2.7.13\lib\site-packages\socks.py", line 667, in _negotiate_SOCKS4
raise SOCKS4Error("{0:#04x}: {1}".format(status, error))
socks.SOCKS4Error: 0x5b: Request rejected or failed
The answer by #pynexj is correct, but having a full working example is always nice:
import socks
import paramiko
sock=socks.socksocket()
sock.set_proxy(
proxy_type=socks.SOCKS5,
addr="proxy.host.name.example",
port=1080,
username="blubbs",
password="blabbs"
)
sock.connect(('ssh.host.name.example', 22))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('ignored without host key verification', username='caesar', sock=sock)
print((ssh.exec_command('ls')[1]).read().decode())
ssh.close()
(Would be nice to know if sock has to be closed separately…)
sock.connect((host, port)) should use the SSH server's hostname (the same host you use for SSHClient.connect()) and port (default 22).
I am trying to implement a simple ftp with sockets using C (server side) and Python (client side). When the server code is compiled and run, the user enters a port number. The client then enters "localhost " when compiling. For some reason I am getting [Errno 111] on the client side when I run the code. It is saying that the issue is with my client.connect statement. I have tried using multiple different port numbers and it throws this same error:
flip1 ~/FTPClient 54% python ftpclientNew.py localhost 2500
Traceback (most recent call last):
File "ftpclientNew.py", line 86, in <module>
main()
File "ftpclientNew.py", line 27, in main
if client.connect((serverName, portNumber)) == None:
File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused
Another weird thing is that this connection error was not happening when I ran this same code a few days ago. Has anyone experienced a problem like this? Any idea what might be causing this? Thanks!
Here is the client code:
import sys, posix, string
from socket import *
def main():
if len(sys.argv) < 3:
print "\nFormat: 'localhost' <port number>!\n"
return 0
buffer = ""
bufferSize = 500
serverName = "localhost"
fileBuffer = [10000]
if sys.argv[1] != serverName:
print "Incorrect Server Name! \n"
return 0
portNumber = int(sys.argv[2])
client = socket(AF_INET, SOCK_STREAM)
if client < 0:
print "Error Creating Socket!! \n"
return 0
if client.connect((serverName, portNumber)) == None:
print "Client Socket Created...\n"
print "Connecting to the server...\n"
print "Connected!\n"
##clientName = raw_input("Enter a file name: ")
Sometimes localhost isn't working on host
Change this
serverName = 127.0.0.1
Try to change the serverName variable to 127.0.0.1.
I've been trying to run commands on an Overture Box using paramiko to establish the SSH connection.
My script does connect properly to the box, no issues are seen, the problem comes when the script runs the exec_command(cmd) method:
Traceback (most recent call last):
File "test.py", line 39, in <module>
stdin, stdout, stderr = ssh.exec_command("version")
File "/opt/csw/lib/python2.7/site-packages/paramiko/client.py", line 345, in exec_command
chan.exec_command(command)
File "/opt/csw/lib/python2.7/site-packages/paramiko/channel.py", line 60, in _check
return func(self, *args, **kwds)
File "/opt/csw/lib/python2.7/site-packages/paramiko/channel.py", line 229, in exec_command
self._wait_for_event()
File "/opt/csw/lib/python2.7/site-packages/paramiko/channel.py", line 1086, in _wait_for_event
raise e
paramiko.ssh_exception.SSHException: Channel closed.
Same script using a Linux Box as the target host yields the proper results
The code is borrowed, I just found the snippet Googling:
import sys
import time
import select
import paramiko
host = raw_input("Hostname?: ")
i = 1
password = raw_input("Password?: ")
#
# Try to connect to the host.
# Retry a few times if it fails.
#
while True:
print "Trying to connect to %s (%i/30)" % (host, i)
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port=22, username="username", password=password)
print "Connected to %s" % host
break
except paramiko.AuthenticationException:
print "Authentication failed when connecting to %s" % host
sys.exit(1)
except:
print "Could not SSH to %s, waiting for it to start" % host
i += 1
time.sleep(2)
# If we could not connect within time limit
if i == 30:
print "Could not connect to %s. Giving up" % host
sys.exit(1)
# Send the command (non-blocking)
stdin, stdout, stderr = ssh.exec_command("version")
# Wait for the command to terminate
while not stdout.channel.exit_status_ready():
# Only print data if there is data to read in the channel
if stdout.channel.recv_ready():
rl, wl, xl = select.select([stdout.channel], [], [], 0.0)
if len(rl) > 0:
# Print data from stdout
print stdout.channel.recv(1024),
#
# Disconnect from the host
#
print "Command done, closing SSH connection"
ssh.close()
I found other questions where it's said that the issue might be related to the SFTP settings in the host, but I'm able to do:
sftp username#hostname
I've Googled for a while but I can't find anything helpful so far.
Thanks in advance for your help.
EDIT: Almost forgot, I know the issue is exactly at:
stdin, stdout, stderr = ssh.exec_command("version")
I've run the whole script interactively and it breaks when I run that line.
Could be that the Overture does not support the SSH exec_command request.
I have needed to use transport.open_session(), and session.get_pty() and session.invoke_shell() to setup an interactive shell session, then use session.send() and session.recv() to write/read to the shell session for Cisco switches and other network appliances, when exec_command() is not available.
here is a workaround for this,
get a transport for your connection.
open a session.
then exec_command(command) and thenrecv()`, no need for sleep.
client.connect("host", port=22, username="user",password= "pass",look_for_keys=False, allow_agent=False)
transport=client.get_transport()
channel = t.open_session()
channel.exec_command(command)
out = channel.recv(-1)
print(out.decode())
Im making a port scanner it through's this message here is my code but it checks one port 21 i have pasted output below
import socket
import os
host = input("Enter the host name or ip : ")
s = socket.socket()
s.settimeout(5)
p = 0;
s.close
port = [21,22,23,25,53,80,110,115,135,139,143,194,443,445,1433,3306,3389,5632,5900,6112]
while(p<=19):
try:
s.connect(('host', port[p]))
except ConnectionRefusedError:
print("Port %d is close" %(port[p]))
except socket.timeout:
print("Port %d is close" %(port[p]))
else:
print("Port %d is open" %(port[p]))
p=p+1;
s.close
On command line :
PS E:\Codes by me\Selenium py> python .\practice.py
Enter the host name or ip : 89.86.98.76
Port 21 is close # it checks one port
Traceback (most recent call last):
File ".\practice.py", line 11, in <module>
s.connect((host, port[p]))
OSError: [WinError 10022] An invalid argument was supplied
You are passing the literal string 'host' as the host. You should be passing the variable host:
s.connect((host, port[p]))
You are also not actually closing the socket each time, since you left off the parentheses in s.close(). But if you did close the socket each time, you would have to create a new socket each time, instead of trying to reuse the same socket. You can't reuse a closed socket.