Connection to test SFTP server on 0.0.0.0 - python

I am trying to connect and upload / download a text file via Python, but I am getting this error:
Traceback (most recent call last):
File "C:\Users\Abdul\OneDrive\Desktop\SFTP neu\main3.py", line 8, in <module>
c.connect(hostname = "0.0.0.0",port = 22, username = "tester", pkey = k)
File "D:\Python\lib\site-packages\paramiko\client.py", line 349, in connect
retry_on_signal(lambda: sock.connect(addr))
File "D:\Python\lib\site-packages\paramiko\util.py", line 283, in retry_on_signal
return function()
File "D:\Python\lib\site-packages\paramiko\client.py", line 349, in <lambda>
retry_on_signal(lambda: sock.connect(addr))
OSError: [WinError 10049] Die angeforderte Adresse ist in diesem Kontext ungültig
I'm using Rebex TinySFTP Server.
At first I thought my host was wrong, but that wasn't it.
In this example I used 0.0.0.0.
Here is my code:
#!/usr/bin/python3
import paramiko
k = paramiko.RSAKey.from_private_key_file("C:\\Users\\Abdul\\OneDrive\\Desktop\\RebexServer\\private-rsa-key.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print("connecting")
c.connect(hostname = "0.0.0.0",port = 22, username = "tester", pkey = k)
print("connected")
commands = ["C:\\Users\\Abdul\\OneDrive\\Desktop\\RebexServer\\data\\testfile.txt", "C:\\Users\\Abdul\\OneDrive\\Desktop\\SFTP neu\\data\\testfile1.txt"]
for command in commands:
print("Executing {0}".format( command ))
stdin , stdout, stderr = c.exec_command(command)
print(stdout.read())
print("Errors")
print(stderr.read())
c.close()

At first I thought my host was wrong, but that wasn't it. In this example I used 0.0.0.0
0.0.0.0 is often used when starting a server to indicate that the server should bind to all available IP addresses. But it's not what you should use in your client.
Use one of the actual IP addresses your server is binding to. If both are on the same machine, try 127.0.0.1 or whatever IP address you are using locally. Addresses starting with 192.168. are common in home and small office networks.

Related

Connect two machines using gRPC

I have a gRPC project that works correctly running server and client on the same machine, but when I try it using different machines in a same wifi network using IPV4, it occurs the following error on client:
Traceback (most recent call last):
File "client.py", line 29, in <module>
run()
File "client.py", line 25, in run
add_reply = stub.Add(add_request)
File "/home/caio/dev/laboratorio/mygrpc/.env/lib/python3.8/site-packages/grpc/_channel.py", line 946, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/home/caio/dev/laboratorio/mygrpc/.env/lib/python3.8/site-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "failed to connect to all addresses; last error: UNKNOWN: ipv4:192.168.100.9:50051: tcp handshaker shutdown"
debug_error_string = "UNKNOWN:failed to connect to all addresses; last error: UNKNOWN: ipv4:192.168.100.9:50051: tcp handshaker shutdown {grpc_status:14, created_time:"2022-12-10T15:21:32.619696358-03:00"}"
>
I've seem people reporting that it worked for them, but it's seemed not be much different, so I have no idea what's missing.
server code:
from os import system
system('clear')
from concurrent import futures
import time
import grpc
from grpc import _server
import sum_pb2
import sum_pb2_grpc
PORT = 50051
HOST = "localhost"
class Servicer(sum_pb2_grpc.SumNumbersServicer):
def Add(self, request, context):
print(request)
add_reply = sum_pb2.AddReply()
add_reply.r = request.a + request.b
# return super().Add(request, context)
return add_reply
def serve():
server:_server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
sum_pb2_grpc.add_SumNumbersServicer_to_server(Servicer(), server)
# serve._add_insecure_port(f"localhost:{PORT}")
server.add_insecure_port(f"{HOST}:{PORT}")
server.start()
print(f"Listenning on port {PORT}")
try:
server.wait_for_termination()
except KeyboardInterrupt:
server.stop(0)
if __name__ == "__main__":
serve()
client code:
from os import system
system('clear')
from concurrent import futures
import time
from random import randint
import grpc
from grpc import _server
import sum_pb2
import sum_pb2_grpc
PORT = 50051
HOST = "localhost"
HOST = "192.168.100.9"
min = 0
max = 100
def run():
with grpc.insecure_channel(f"{HOST}:{PORT}") as channel:
stub = sum_pb2_grpc.SumNumbersStub(channel)
a = randint(min, max)
b = randint(min, max)
add_request = sum_pb2.AddRequest(a= a, b= b)
add_reply = stub.Add(add_request)
print(f"{a} + {b} = {add_reply}")
if __name__ == "__main__":
run()
EDIT:
When using "0.0.0.0" as host in server.py it prints the following error (differently from last time, this time I'm using ethernet cable on both machines, idk if it makes difference ):
Traceback (most recent call last):
File "client.py", line 29, in <module>
run()
File "client.py", line 25, in run
add_reply = stub.Add(add_request)
File "/home/estagiarioti/dev/laboratorio/mygrpc/.env/lib/python3.8/site-packages/grpc/_channel.py", line 946, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/home/estagiarioti/dev/laboratorio/mygrpc/.env/lib/python3.8/site-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "failed to connect to all addresses; last error: UNKNOWN: ipv4:192.168.10.6:50051: Failed to connect to remote host: No route to host"
debug_error_string = "UNKNOWN:failed to connect to all addresses; last error: UNKNOWN: ipv4:192.168.10.6:50051: Failed to connect to remote host: No route to host {grpc_status:14, created_time:"2022-12-12T13:58:15.049856347-03:00"}"
>
Error message when running both machines in an wifi network and "0.0.0.0" ip in host:
Traceback (most recent call last):
File "client.py", line 29, in <module>
run()
File "client.py", line 25, in run
add_reply = stub.Add(add_request)
File "/home/caio/dev/laboratorio/mygrpc/.env/lib/python3.8/site-packages/grpc/_channel.py", line 946, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/home/caio/dev/laboratorio/mygrpc/.env/lib/python3.8/site-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "failed to connect to all addresses; last error: UNKNOWN: ipv4:192.168.100.9:50051: tcp handshaker shutdown"
debug_error_string = "UNKNOWN:failed to connect to all addresses; last error: UNKNOWN: ipv4:192.168.100.9:50051: tcp handshaker shutdown {created_time:"2022-12-12T19:12:13.762636131-03:00", grpc_status:14}"
>
ps: Sometimes i use WSL, sometimes i don't, maybe this is important to know.
localhost usually resolves to 127.0.0.1 which is a special so-called loopback network address. It is used when you know that you don't need external (to the host) connectivity because it generally doesn't use the host's network stack.
You will generally want to bind the server to 0.0.0.0 instead. This binds the server to all the host's network interfaces and is a simple way to ensure that your service is available to external hosts.
Also, you will need to be confident that the server's host's network address is 192.168.100.9 to ensure that the client tries to communicate with the correct host.
I don't know what I was doing wrong in WSL, but it worked when I used pure Windows and in the Firewall settings I allowed all the pythons in the list to have access in public and private networks. This with both machines on the same Wifi network

Why Netmiko does not use the dynamically assigned (hostname) IP address for connection?

I have a basic question. I use Nornir to trigger Netmiko to configure a Cisco router. It only works, when I hardcode the IP address in the host inventory (hostname).
Europe-Cisco-Site1:
hostname: "" <-- when I put the public IP here, it works!
username: "ec2-user"
password: ""
platform: "cisco_xe"
groups:
- cisco
connection_options:
netmiko:
extras:
use_keys: true
key_file: "/home/coder/.ssh/id_rsa"
In my case, I have to get the public IP from AWS and then assign the hostname variable dynamiclly:
def assign_aws_public_ips(task):
task.host['hostname'] = get_aws_public_ip(str(task.host), task.host['aws_region'])
print("****************************")
print(task.host['hostname'])
print("****************************")
result = task.run(
task=netmiko_send_config,
config_file="templates/simple.j2"
)
print_result(result)
return(f"{task.host} = {task.host['hostname']}")
This is only a test script to validate, if the public IP is assigned on the hostname:
****************************
**52.59.216.193** <-- this is the public IP which has been assigned to **hostname**
****************************
netmiko_send_config*************************************************************
* Europe-Cisco-Site1 ** changed : False ****************************************
vvvv netmiko_send_config ** changed : False vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ERROR
Traceback (most recent call last):
File "/home/coder/.local/lib/python3.8/site-packages/nornir/core/task.py", line 99, in start
r = self.task(self, **self.params)
File "/home/coder/.local/lib/python3.8/site-packages/nornir_netmiko/tasks/netmiko_send_config.py", line 24, in netmiko_send_config
net_connect = task.host.get_connection(CONNECTION_NAME, task.nornir.config)
File "/home/coder/.local/lib/python3.8/site-packages/nornir/core/inventory.py", line 494, in get_connection
self.open_connection(
File "/home/coder/.local/lib/python3.8/site-packages/nornir/core/inventory.py", line 546, in open_connection
conn_obj.open(
File "/home/coder/.local/lib/python3.8/site-packages/nornir_netmiko/connections/netmiko.py", line 59, in open
connection = ConnectHandler(**parameters)
File "/home/coder/.local/lib/python3.8/site-packages/netmiko/ssh_dispatcher.py", line 326, in ConnectHandler
return ConnectionClass(*args, **kwargs)
File "/home/coder/.local/lib/python3.8/site-packages/netmiko/cisco/cisco_ios.py", line 17, in __init__
return super().__init__(*args, **kwargs)
File "/home/coder/.local/lib/python3.8/site-packages/netmiko/base_connection.py", line 244, in __init__
raise ValueError("Either ip or host must be set")
ValueError: Either ip or host must be set
Question:
Why does Netmiko don't use the hostname, which has been assigned during the play? It always takes the hostname which has not been defined in the host inventory file?
One bad solution would be to update the host inventory file with the public IP but this is really a bad solution and I can’t imagine that this should be done!?
Got it now!!!! Missed really something basic, I though I can use hostname like a dictionary but this is not true. Thanks for the help!
This is the correct code:
def assign_aws_public_ips(task):
task.host.hostname = get_aws_public_ip(str(task.host), task.host['aws_region'])
return(f"{task.host} = {task.host.hostname}")
This is the right Tutorial where the Well-knonw Attributes are described, for reference:
https://gist.github.com/danielmacuare/c647880cfc99a605d25c3b669ab63fc7

How to run pycrate corenet

I want to run the core simulator of https://github.com/P1sec/pycrate.
And I want to run SERVER_ENB only, so configure like below and create a server.
from pycrate_corenet import Server
Server.CorenetServer.SERVER_HNB = {}
Server.CorenetServer.SERVER_ENB['IP'] = '127.0.0.1'
Server.CorenetServer.SERVER_ENB['GTPU'] = '127.0.0.1'
epc = Server.CorenetServer()
But, I got following error.
$ sudo /usr/local/anaconda3/bin/python EPC.py
CorenetServer: loading all ASN.1 and NAS modules, be patient...
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/anaconda3/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/local/anaconda3/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/anaconda3/lib/python3.6/site-packages/pycrate-0.3-py3.6.egg/pycrate_corenet/Server.py", line 345, in start
self.GTPUd = self.__class__.GTPUd()
File "/usr/local/anaconda3/lib/python3.6/site-packages/pycrate-0.3-py3.6.egg/pycrate_corenet/ServerGTPU.py", line 466, in __init__
sk.bind((gtpip, self.GTP_PORT))
OSError: [Errno 99] Cannot assign requested address
How can I run the server?
Could you give a usage for this pycrate corenet?
this port is probably occupied by something else (including the other instance on this server).
If you're on Linux - you can check if it's already listen with netstat -anp | grep 36412. Then if something listed there you have to kill the app or change server's port in SERVER_ENB structure
I got a solution.
from pycrate.pycrate_corenet import Server, ServerGTPU
Server.CorenetServer.SERVER_HNB = {}
Server.CorenetServer.SERVER_ENB['IP'] = '127.0.0.1'
Server.CorenetServer.SERVER_ENB['GTPU'] = '127.0.0.1'
ServerGTPU.GTPUd.GTP_IF = ['127.0.0.1'] # set GTP IP
epc = Server.CorenetServer()

Paramiko script with error

I've found the following script on internet:
import paramiko
from paramiko import client
class ssh:
client = None
def __init__(self, address, username, password):
# Let the user know we're connecting to the server
print("Connecting to server.")
# Create a new SSH client
self.client = client.SSHClient()
# The following line is required if you want the script to be able to access a server that's not yet in the known_hosts file
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
# Make the connection
self.client.connect(address, username=username, password=password, look_for_keys=False)
def sendCommand(self, command):
# Check if connection is made previously
if (self.client):
stdin, stdout, stderr = self.client.exec_command(command)
while not stdout.channel.exit_status_ready():
# Print stdout data when available
if stdout.channel.recv_ready():
# Retrieve the first 1024 bytes
alldata = stdout.channel.recv(1024)
while stdout.channel.recv_ready():
# Retrieve the next 1024 bytes
alldata += stdout.channel.recv(1024)
# Print as string with utf8 encoding
print(str(alldata, "utf8"))
else:
print("Connection not opened.")
paramiko.util.log_to_file('paramiko.log') # <----- added line
connessione = ssh("10.76.80.11","pi","raspberry")
connessione.sendCommand("arp -a")
I would like to send a commando to my raspberry with this script, I tried to run the program without the line:
paramiko.util.log_to_file('paramiko.log')
but when I tried to run the code I've got this runtime error:
/usr/bin/python /Users/Marco/PycharmProjects/ssh_control/ssh.py
Connecting to server.
No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last):
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 43, in <module>
connessione = ssh("10.76.80.11","pi","raspberry")
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 16, in __init__
self.client.connect(address, username=username, password=password, look_for_keys=False)
File "/Users/Marco/Library/Python/2.7/lib/python/site-packages/paramiko/client.py", line 338, in connect
t.start_client()
File "/Users/Marco/Library/Python/2.7/lib/python/site- packages/paramiko/transport.py", line 493, in start_client
raise e
AttributeError: 'EntryPoint' object has no attribute 'resolve'
Process finished with exit code 1
So I searched on Internet and I found that the problem could be fixed with the paramiko.log line.
But now I've another error:
/usr/bin/python /Users/Marco/PycharmProjects/ssh_control/ssh.py
Connecting to server.
Traceback (most recent call last):
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 38, in <module>
connessione = ssh("10.76.80.11","pi","raspberry")
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 16, in __init__
self.client.connect(address, username=username, password=password, look_for_keys=False)
File "/Users/Marco/Library/Python/2.7/lib/python/site- packages/paramiko/client.py", line 338, in connect
t.start_client()
File "/Users/Marco/Library/Python/2.7/lib/python/site-packages/paramiko/transport.py", line 493, in start_client
raise e
AttributeError: 'EntryPoint' object has no attribute 'resolve'
Process finished with exit code 1
Can someone helps me please? because I can't understand where is the error.
Thanks in advance
Turns out you need to upgrade setuptools and then re-install the package. Seems the older version breaks something on installing the python cryptography package.
Try the following...
pip install -U setuptools
pin install -U paramiko
https://github.com/pyca/cryptography/issues/2853
I solved my problem with this:
# Make the connection
self.client.connect(address, port = 22, username=username, password=password, look_for_keys=False)
because the port before wasn't specificate

Network is unreachable if running script on webhosting

The next script runs fine on my mac. When I try to run it on my WebHosting (bluehost) I'm getting socket.error: [Errno 101] Network is unreachable. Any idea how can I fix it?
#!/usr/bin/python
# Required header that tells the browser how to render the text.
print "Content-type: text/html\r\n\r\n";
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('user#gmail.com', 'password')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
print mail.list()
Traceback (most recent call last):
File "test2.py", line 6, in <module>
mail = imaplib.IMAP4_SSL('imap.gmail.com')
File "/home4/user/python27/lib/python2.7/imaplib.py", line 1148, in __init__
IMAP4.__init__(self, host, port)
File "/home4/user/python27/lib/python2.7/imaplib.py", line 163, in __init__
self.open(host, port)
File "/home4/user/python27/lib/python2.7/imaplib.py", line 1159, in open
self.sock = socket.create_connection((host, port))
File "/home4/user/python27/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 101] Network is unreachable
Their support isn't helpful at all.
Can it be port related or maybe SSL?
On bluehosts help pages they mention that outgoing connnections are restricted, so ther problem isn't with your program. The only way of getting outbound connections to be allowed seems to pay for it.

Categories

Resources