paramiko Error Servname not supported for ai_socktype - paramiko

I am unable to connect to other server through paramiko:
import paramiko
import sys
import os
hostname = 'server1'
port = 22
username = 'root'
password = 'password'`enter code here`
def deploy_key(key, hostname, username, password):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, username, password)
client.exec_command('mkdir -p ~/.ssh/')
client.exec_command('echo "%s" > ~/.ssh/authorized_keys' % key)
client.exec_command('chmod 644 ~/.ssh/authorized_keys')
client.exec_command('chmod 700 ~/.ssh/')
key = open(os.path.expanduser('~/.ssh/id_rsa.pub')).read()
deploy_key(key, hostname, username, password)
Here was the output:
socket.AF_UNSPEC, socket.SOCK_STREAM):
socket.gaierror: [Errno -8] Servname not supported for ai_socktype

The problem is with the call to client.connect(). It expects port to be second parameter and to be an integer, whereas you are giving username (string) as second parameter.
Try replacing that with below line.
client.connect(hostname, username=username, password=password)
That should work.

Related

ValueError: invalid literal for int() with base 10: 'Oompa Loompa\x07\x08'

I have the TCP server set up for receiving messages from connected clients, but when the message contains packed hex e.g "Oompa Loompa\x07\x08" it shows me this error:
ValueError: invalid literal for int() with base 10: 'Oompa Loompa\x07\x08'
I guess I have decoding issue in the code but I don't know how to fix it.
import socket
import threading
HEADER = 64
PORT = 5050
SERVER = "192.168.1.103"
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
print(f"[{addr}] {msg}")
conn.send("Msg received".encode(FORMAT))
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[Active Clients] {threading.active_count() - 1}")
print("[BOOTING] server is starting...")
start()
It seems like hex is a strings and needs to be an int. Try sending that message in binary.

Python smtplib.SMTP('localhost') hangs forever

I have a server with installed Postfix SMTP service, and I can send messages using bash like this:
echo "This is the body of the email" | mail -s "This is the subject line" user#example.com
But when I'm trying to do the same with Python it hangs forever:
import smtplib
s = smtplib.SMTP('localhost')
s.send_message('')
The script hangs on the second line, and it is not clear why.
I've checked the configuration of iptables (it is empty) and I still able to send messages with bash command.
"telnet localhost 25" also works fine, port is open.
Postfix config file:
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = localhost
mynetworks = 127.0.0.0/8
myorigin = /etc/mailname
send_message() expects an EmailMessage not a string. Currently it appears to hang because postfix is waiting for you to tell it to do something, you can enable debugging output using set_debuglevel().
Here's a simple example that should work:
from email.message import EmailMessage
import smtplib
msg = EmailMessage()
msg["From"] = "user#example.com"
msg["To"] = "another-user#example.com"
msg["Subject"] = "Test message subject."
msg.set_content("Test message.")
s = smtplib.SMTP("localhost")
s.set_debuglevel(1)
s.send_message(msg)
s.quit()

Unable to connect Corda node to Postgres with SSL

My Postgres DB in GCP (Google Cloud Platform) only accepts connections over SSL.
I tried the below inside my node.conf without any success:
dataSourceProperties {
dataSourceClassName = "org.postgresql.ds.PGSimpleDataSource"
dataSource.url = "jdbc:postgresql://db-private-ip:5432/my_node"
dataSource.ssl = true
dataSource.sslMode = verify-ca
dataSource.sslRootCert = "/opt/corda/db-certs/server-ca.pem"
dataSource.sslCert = "/opt/corda/db-certs/client-cert.pem"
dataSource.sslKey = "/opt/corda/db-certs/client-key.pem"
dataSource.user = my_node_db_user
dataSource.password = my_pass
}
I'm sure that the keys (sslMode, sslRootCert, sslCert, and sslKey) are acceptable in node.conf (even though they are not mentioned anywhere in Corda docs), because in the logs I didn't get any errors that those key are not recognized.
I get this error when I try to start the node:
[ERROR] 21:58:48+0000 [main] pool.HikariPool. - HikariPool-1 - Exception during pool initialization. [errorCode=zmhrwq, moreInformationAt=https://errors.corda.net/OS/4.3/zmhrwq]
[ERROR] 21:58:48+0000 [main] internal.NodeStartupLogging. - Could not connect to the database. Please check your JDBC connection URL, or the connectivity to the database.: Could not connect to the database. Please check your JDBC connection URL, or the connectivity to the database. [errorCode=18t70u2, moreInformationAt=https://errors.corda.net/OS/4.3/18t70u2]
I tried adding ?ssl=true to the end of the data source URL as suggested in (Azure Postgres Database requires SSL Connection from Corda) but that didn't fix the problem.
Also for the same values I'm able to use the psql client to connect my VM to the DB:
psql "sslmode=verify-ca sslrootcert=server-ca.pem sslcert=client-cert.pem sslkey=client-key.pem hostaddr=db-private-ip user=some-user dbname=some-pass"
Turns out the JDBC driver cannot read the key from a PEM file, it has to be converted to a DER file using:
openssl pkcs8 -topk8 -inform PEM -in client-key.pem -outform DER -nocrypt -out client-key.der
chmod 400 client-key.der
chown corda:corda client-key.der
More details here: https://github.com/pgjdbc/pgjdbc/issues/1364
So the correct config should look like this:
dataSourceProperties {
dataSourceClassName = "org.postgresql.ds.PGSimpleDataSource"
dataSource.url = "jdbc:postgresql://db-private-ip:5432/db-name"
dataSource.ssl = true
dataSource.sslMode = verify-ca
dataSource.sslRootCert = "/opt/corda/db-certs/server-ca.pem"
dataSource.sslCert = "/opt/corda/db-certs/client-cert.pem"
dataSource.sslKey = "/opt/corda/db-certs/client-key.der"
dataSource.user = db-user-name
dataSource.password = db-user-pass
}

why do I see TypeError for python socket module?

I am learning python, and these days I am trying to work with socket module. Below is the client side logic.
import socket
from threading import Thread
import ipaddress
lic_server_host = input("Please enter the hostname: ")
port = input("Please enter the License service port number: ")
client_socket = socket.socket()
client_socket.connect((lic_server_host, port))
def receive_data():
while True:
data = client_socket.recv(1000)
print(data.decode())
def sending_data():
while True:
user_input = input()
client_socket.sendall(user_input.encode())
t = Thread(target=receive_data)
t.start()
sending_data()
Here I am taking user's input as a hostname. However. The above porgram is not able to convert the hostname to integer. I am getting below error
client_socket.connect((lic_server_hostname, port))
TypeError: an integer is required (got type str)
I tried to use some python way to get rid of the issue by introducing for loop on the user's input as below
lic_server_host = input("Please enter the License server hostname: ")
for info in lic_server_hostname:
if info.strip():
n = int(info)
port = input("Please enter the License service port number: ")
client_socket = socket.socket()
client_socket.connect((n, port))
But now I get below error:
client_socket.connect((n, port))
TypeError: str, bytes or bytearray expected, not int
So based on the error I used str() function on "n". But when I do that I get below error:
n = int(info)
ValueError: invalid literal for int() with base 10: 'l'
I have also searched for the above error available on the internet but the solutions not helping me.
Please help me understand my mistake.
Thank you
input returns a string when connect requires port as int.
client_socket.connect((lic_server_host, int(port)))

When calling a function, how to feed variable as an arg

I have the code below that works, but instead of calling the function with "www.google.com", i need to be able to pass as arg:
python certexp.py www.google.com:
import ssl
import OpenSSL
import time
def get_SSL_Expiry_Date(host, port):
cert = ssl.get_server_certificate((host, 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
raw_date = x509.get_notAfter()
decoded_date = raw_date.decode("utf-8")
print (decoded_date)
dexpires = time.strptime(decoded_date, "%Y%m%d%H%M%Sz")
print (dexpires.tm_mon,"/",dexpires.tm_mday,"/",dexpires.tm_year)
get_SSL_Expiry_Date("google.com", 443)
Thank you
In python the sys module handles command line arguments.
This gives you an array of command line parameters, with sys.argv[0] being the name of the executable, then any subsequent elements being user parameters.
This makes your code:
import ssl
import OpenSSL
import time
import sys
def get_SSL_Expiry_Date(host, port):
cert = ssl.get_server_certificate((host, 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
raw_date = x509.get_notAfter()
decoded_date = raw_date.decode("utf-8")
print (decoded_date)
dexpires = time.strptime(decoded_date, "%Y%m%d%H%M%Sz")
print (dexpires.tm_mon,"/",dexpires.tm_mday,"/",dexpires.tm_year)
if (len(sys.argv) == 1):
sys.stderr.write("%s: Give hostname as an argument, optionally a port too" % (sys.argv[0]))
sys.exit(1)
hostname = sys.argv[1]
port = 443
if (len(sys.argv) == 3):
port = int(sys.argv[2])
get_SSL_Expiry_Date(hostname, port)
Obviously you could do that for the port too. There's other command line parsing modules too, so you can say --port= etc.

Resources