Establishing SSH connection using Python - python

This is the first time I'm asking a question on stackoverflow, so do inform me if I should ask questions differently or provide additional data.
I have an ssh command that I run on my command prompt to connect to postgreSQL server
ssh -L 5433:<host>:5432 -i <public_key> <username>#<IP address> -p 1024 -N
I try run the same through a python script, when I run it using
os.system("ssh -L 5433:<host>:5432 -i <public_key> <username>#<IP address> -p 1024 -N")
conn1 = None
conn1 = psycopg2.connect(dbname="db",user="username",
host="localhost", password="xxxx",port="5433")
It throws me the following error,
could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5433?
I have tried using paramiko to connect to the same, but I'm unable to translate the command line that I have to all the parameters required, for example, I don't understand port1:xxx:port2 and how to implement that in paramiko, the same goes for the public key. Given below is the code I use for that,
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('<hostname>', username='<username>, key_filename='<public_key>')
I've looked through many documentations but can't find a solution to the same. Any help is massively appreciated.

Related

SSH from shell terminal to another server & execute commands using python paramiko [duplicate]

This question already has an answer here:
Connecting to a server via another server using Paramiko
(1 answer)
Closed 2 years ago.
import time
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('x.x.x.x',22, username='root', password='12345')
ssh_stdin ,ssh_stdout, ssh_stderr = ssh.exec_command('ssh -tt root#y.y.y.y')
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('test#123')
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('!pwd')
This is the code i want to run i want to login to shell terminal of x.x.x.x server & ssh to server y.y.y.y & excute several commands. please help me on this
Try sshpass package.
The problem looks like that after you execute the first command, it is expecting the password, but the command is not returned to the client.
You can try installing sshpass first into x.x.x.x, and then use it like this:
sshpass -p 'YourPassword' ssh user#y.y.y.y
to login to y.y.y.y.

Connecting to PostgreSQL database through Python code

I have a Ubuntu virtual machine using Vagrant, I set it up and run it using vagrant up and vagrant ssh and I create the database psql -d dbname -f somesqlqueries.sql.
Whenever I try to connect to this database through python by doing conn = psycopg2.connect("dbname=dbname") I get this error:
psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
Looking at solutions for this issue I changed postgresql.conf to have listen_address = '*' and still the same error occurs.
Also tried to turn off the firewall and run sudo ufw allow 5432/tcp and the error still persistent.

Python pxssh execute iptables not working

I'm using pxssh to establish an SSH connection to a server. To connection can be establish and I can run simple commands such as ls -l.
What I need now is to create iptable entries via that SSH connection.
I've tried the following
s = pxssh.pxssh()
print(ip)
if not s.login(ip, username, auth_password):
Log("SSH session failed on login")
Log(str(s))
else:
Log("SSH session login successful")
cmd = 'sudo iptables -I INPUT -p udp -m udp --dport 53 -j ACCEPT;'
s.sendline(cmd)
s.prompt()
print(s.before)
s.logout()
which runs without error, but when connection to the server, no iptable entry had been created!?
Try modifying your python script like this:
cmd = '/usr/bin/sudo /usr/sbin/iptables -I INPUT -p udp -m udp --dport 53 -j ACCEPT'
s.sendline(cmd)
You should change the sudo and iptables path if it's different on your OS
Also try printing the s.sendline(cmd) to see what actually is executed via the ptyhon script on the server, just to be sure that the correct iptables command is executed

Access Ipython Notebook Running on Remote Server

Have installed Anaconda Python on remote linux machine.
Used putty on local Windows to login to remote linux machine to remotely start the Ipython Notebook. It's started on port 8888.
remote_user#remote_host$ ipython notebook --no-browser --port=8888
Now I need to access this Notebook on local browser.
Have tried doing ssh tunnel.
C:\Users\windowsUser> ssh -N -f -L localhost:8888:localhost:8888 remote_user#remote_host
ssh: connect to host remote_host port 22: Bad file number
But not able to get it right. Getting the above error
Note: the user windowsUser does not exist on remote_host(linux). Remote user account is remote_user.
Where am i going wrong?
Plzz help
It appears you have a typo. In your ssh command you should not have "localhost" twice.
The corrected command is:
ssh -N -f -L 8888:localhost:8888 remote_user#remote_host
Because the syntax for the command is:
ssh -L <Local Port>:<Local Machine>:<Target Port> <Target Machine>
(see http://www.slashroot.in/ssh-port-forwarding-linux-configuration-and-examples)
Furthermore, you could instead modify your ssh config file (in ~/.ssh/config or /etc/ssh_config) to include port forwarding:
Host remote_host
Hostname PUT_REMOTE_IP_HERE
Port 22
User remote_user
LocalForward 8888 localhost:8888
I don't think window has a ssh cmd,
if local is a standard ssh client use
C:\Users\windowsUser> ssh -N -f -L 8888:localhost:8888 remote_user#remote_host
BTW
ipython notebook --ip=remote_host_ip
then you can access with http://remote_host_ip:8888/tree

Why am I receiving a low level socket error when using the Fabric python library?

When I run the command:
fab -H localhost host_type
I receive the following error:
[localhost] Executing task 'host_type'
[localhost] run: uname -s
Fatal error: Low level socket error connecting to host localhost: Connection refused
Aborting.
Any thoughts as to why? Thanks.
Fabfile.py
from fabric.api import run
def host_type():
run('uname -s')
Configuration
Fabric 1.0a0 (installed from the most recent Github commit---b8e1b6a)
Paramiko 1.7.4
PyCrypto 2.0.1
Virtualenv ver 1.3.3
Python 2.6.2+ (release26-maint:74924, Sep 18 2009, 16:03:18)
Mac OS X 10.6.1
The important part isn't the "low level error" part of the message - the important part is the "Connection refused" part. You'll get a "connection refused" message when trying to connect to a closed port.
The most likely scenario is that you are not running an ssh server on your machine at the time that Fabric is running. If you do
ssh localhost
you'll probably get a message similar to
ssh: connect to host localhost: Connection refused
So you'll have to go out and set up an SSH server on your computer before you can proceed with Fabric from there.
I had the same problem, but the reason was different: While I could easily log in to the server via SSH (default port 22), fabric tried to connect on a closed port 9090.
Finally I recognized that I had defined "env.port=9090" in my old fabfile for some WSGI server setup; while that was never a problem, I updated my Python installation some weeks before, and fabric now uses env.port for its SSH connection.
I just renamed that config, and all is well again.
This can also happen in OS X 10.11.4 and Fabric 1.10.1, in the case where you are ssh'ing to a VM using Vagrant, which does port forwarding from localhost. In this case, localhost was resolving to the IPv6 ::1 address (not due to /etc/hosts file), and giving this error.
The fix was to force use of IPv4 by using the 127.0.0.1 address in the fabfile instead of the hostname. Using a hostname in /etc/hosts with this address didn't work.
You might also want to try these useful tips for debugging connection issues in Fabric.
env.roledefs = {
'role1': env.hosts[0:5],
'role2':[env.hosts[5],]
}
I encountered the same error if "role" value IS NOT A LIST. for example, the above code works but the following doesn't.
env.roledefs = {
'role1': env.hosts[0:5],
'role2':env.hosts[5],
}

Categories