Retrieving netstat from local server python script - python

How do i retrieve the netstat -a data from my python script from a local server. I have tried subprocess.Popen(['ssh','server','pass','netstat','-a'],stdout=file1) but it does not work. Any advice?

You must have key based authorisation from the desired server where netstat is suppose to run.
In the absence on key based authorisation, the ssh command will return a prompt asking for password.
Below is the link for key based authorisation:
http://wp.uberdose.com/2006/10/16/ssh-automatic-login/
or
http://linuxproblem.org/art_9.html
Once the keys are exchanged, the command mentioned in your question does not require any password and no prompt will occur when you run it.
subprocess.Popen(['ssh','server','netstat','-a'],stdout=file1)

Related

Make a single SSH connection via paramiko and send a command to check the hostname and a 2nd command to see if there is anything in the www directory

Your manager just asked you to find out what is the hostname (/etc/hostname) and if there are any files in the www directory. Your manager wants you to check this on two Ubuntu-based machines. However, they want you to have this written in a way that will scale to all 100 servers on the network. Achieve the following items:
Make a Flowchart.
Create Pseudocode.
Make a single SSH connection via paramiko and send a command to check the hostname and a second command to see if there is anything in the www directory.
Input the IP addresses from a file (text or CSV).
Save the output of both commands, make sure to note what IP the data came from, to a file (text or CSV).
As mirlinda said, this is a set of requirement rather than a question. I just have a plan for your information.
You can write all ip address to text file with one ip per line.
Use ssh-keygen -t rsa -C "your mail" command to create ssh rsa key in your 100 servers.
Run ssh-copy-id -i ~/.ssh/id_rsa.pub root#[ip] to make your administrator machine can access which server you want to access without password.
Write a python script to read one ip per time from the text file saved your all server ip by readline interface.
And use check_output interface to run hostname command to get server host name and ls [full path of www] to get contents of www directory.
You just can save return contents of check_output interface to a file by redirection symbol '>'.
Loop operations 4-6 in your python script by using while or for statement until get all host name and contents of www of all 100 servers.

Unable to send AT commands trough Paramiko SSH [duplicate]

This question already has an answer here:
Executing command using Paramiko exec_command on device is not working
(1 answer)
Closed 2 years ago.
I'm working on a GPS position retrieval project, I have to connect in SSH on routers, then launch commands to retrieve latitude and longitude.
I recently received new routers, when we connect to this router, we receive an "OK" signal when we are connected to ensure proper operation, then we run the command we want, and we get the data as in this example below, always followed by the "OK" message indicating that the command worked well :
AT*GNSSSTATUS?
Location Fix=1
Number of satellites = 14
Latitude=+49.17081
Longitude=-123.06970
Date=2016/02/29
Time= 18:55:28
TTFF=9449 milliSeconds
OK
When I connect in SSH with the help of PUTTY, it works, but when I use my code that sends the same command as mentioned above (AT*GNSSSTATUS?) through my Python script and the Paramiko library, the result is just "OK" which indicates that the connection is just active. It's like the command line opened by the script doesn't take the "ENTER" that should come next.
To test this, I tried to put a command returning "ERROR" in case I use PUTTY, but even in this case the Python script returns "OK".
To try to fix this I tried different options by adding :
stdin, stdout, stderr = client.exec_command('AT*GNSSSTATUS? \r\n')
or
stdin, stdout, stderr = client.exec_command('AT*GNSSSTATUS? <CR>')
But in no case does this change the result.
My data list contains only one string marked "OK".
For the connection part on the router everything works.
Anyone have any ideas?
Thanks a lot!
Sorry if there are spelling mistakes ahah.
Thanks Martin Prikryl !
So I looked at the link you sent me and it worked:
Executing command using Paramiko exec_channel on device is not working.
So I changed my code to use a shell and send my commands through it.
Here is my code
shell = client.invoke_shell()
shell.send('AT*GNSSSTATUS? \r')
Thank you very much and have a nice day

Recommend Way to Interact with an SSH session in Python

I'm working on a little python program to speed up managing various Raspberry Pi servers over SSH. It's all done but for one thing. Interacting with an SSH session isn't wokring the way I want it to.
I can interact with a command but some commands (specifically apt full-upgrade) which ask or have potential to ask questions whilst they're running aren't working. So when it reaches the point where it asks do you want to continue [Y/n] it falls over. I believe it's because apt can't read from the stdin so aborts.
I know I could run the apt command with the -y flag and bypass the question but ideally I'd like to be able to capture requests and ask the user for input. I've been using Paramiko to manage my SSH sessions and what I'm doing is capturing the stdout and passing it to the find function to look for things like [Y/n] and if it finds that then redirect the user to an input prompt which works but because theres no stdin when apt asks the question it aborts and when I send my user input back to the SSH session I get a socket closed error.
I've been looking for alternatives or ways to get round the issue but apart from seeing fabric mentioned as an alternative to paramiko I can't see a lot of other options out there. Does anyone know of any alternatives I can try to paramiko. I don't think fabric will work for me given its based off paramiko so I assume I'd hit the same error there. I'd appreciate any recoomendations or pointers if there's other parts of Paramiko I can try (I've stuck to using exec_command). I have tried channels which work to a point but I don't think keeping the SSH session open is the issue I think I need someway to keep stdin open/accessible to the apt command on the remote machine so it doesn't abort the command.
At the minute the best idea I've got to get round it is to run the command let it potentially abort look in stdout for the relevant phrases then run the command again after giving the user chance to set their inputs and pass the whole lot to stdin?
EDIT:
My program in steps:
login to the remote host
issue a command
use .find on the command to check for the use of 'sudo'
if sudo is present additionally send the user password to stdin along with the command
read the stdout to check for keywords/phrases like '[Y/n]' which are present when the user is being asked for input when running a command
if a keyword is found then ask the user for their input which can then be sent back to stdin to continue the command.
Steps 5 and 6 are where it fails and returns with a socket closed error. Looking online I don't think the issue is with paramiko as such but with the command running on the remote host. In my case sudo apt full-upgrade.
When I run that command it runs up to the 'Would you like to continue' point the automatically aborts, I believe the issue there is because there is nothing present in the stdin at that point (thats what I'm asking the user for) Apt automatically aborts
This is the part of my code where I'm running the commands:
admin = issue_cmd.find('sudo')
connect.connect(ip_addr, port, uname, passwd)
stdin, stdout, stderr = connect.exec_command(issue_cmd, get_pty=True)
if admin != -1:
print('Sudo detected. Attempting to elevate privileges...')
stdin.write(passwd + '\n')
stdin.flush()
else:
continue
output = stdout.read()
search = str(output).find('[Y/n]')
if search != -1:
resp = input(': ')
print(resp)
stdin.write(resp + '\n')
stdin.flush()
else:
pass
print(stdout.read().decode('utf-8').strip("\n"))
print(stderr.read().decode('utf-8').strip("\n"))
connect.close()
and here's the error message I'm seeing:
OSError: Socket is closed

SSH using Python via private keys

In my script, I need to do an SSH to a remote system using a private key and dump the file into its directory.
The command I am using to SSH into the system is this:
ssh -i private_key localhost
Followed by the standard input:
Enter passphrase for key 'private_key'
I am trying to do this in a Python script, but am not sure about the way of writing a command and passing a passphrase as a parameter so that the whole sequence can be automated.
Please suggest me a way to achieve this via a library (Paramiko SSHClient) or a code snippet would be highly really appreciated.
SSHClient.connect can handle public key authentication with a simple call:
import paramiko
ssh = paramiko.SSHClient()
ssh.connect(hostname, username=username, key_filename=key_path, password=passphrase)
The password argument is used as a passphrase, when key_filename is provided.
Additionally, you will also have to verify the server's host key (as you must have done with ssh before). See Paramiko "Unknown Server".

Paramiko connect without asking ssh key

This is my python script to connect to server. But when I run the script, it is asking me to keying my ssh passphrase. How could I avoid to asking my ssh passphrase key?
host = '192.168.43.3'
user = 'root'
passwd = 'ppawd'
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=passwd)
transport = ssh.get_transport()
channel = transport.open_session()
channel.setblocking(1)
channel.settimeout(30)
command = "ls -a"
ssh.exec_command(command)
I ran into the same issue. I don't think the other answers here realized what the question was actually for. This is an old question but I wanted to help anyone else like me who ended up here after googling.
You need to disable the ssh agent feature allow_agent=False and then it will no longer prompt you for a passphrase. Paramiko is trying to connect to the ssh agent and I assume trying to read the key. I also added look_for_keys=False, as it will disable checking for private keys to use.
Example:
client.connect(server, port=port, username=username, password=password, look_for_keys=False, allow_agent=False)
My advice would be generating a key without a passphrase - just press enter when asked for a password while creating the key.
This key should be used specifically for your script - avoid re-using keys you use for other purposes (such as your user's interactive login), since it makes key revocation and access control harder.
A passphrase-less key has some advantages compared to hardcoding the password in your script:
The presence of a passphrase-less key makes it clear to anyone that the key is compromised as soon as anyone has access to it. Separating the password from the key hides this fact without providing any additional security.
It avoids you publishing your password to source-control accidentally (separation of source code and access control credentials)
Possibly, it'll make it less tempting to re-use any existing user's ssh key with a proper passphrase.
A few security considerations:
Remember that anyone with access to that key will get access to the remote system. You may consider putting restrictive permissions on the key file, and create a separate user for your script to login into in the remote system, if it's possible at all.
If your script is single purpose, you may also consider limiting the list of shell commands available to the user on the remote system
If you have no physical security on the system that stores the key (i.e.: a laptop or desktop in a untrusted location), you may also want to use full disk encryption, block device encryption (LUKS) or file-level encryption (encfs).
I solved the problem as
ssh-copy-id root#192.168.43.133
Credit to http://sshmenu.sourceforge.net/articles/key-setup.html
You can add the fingerprint to each server's known_hosts. For a single user:
cat ~/.ssh/known_hosts
echo "$SERVER,$PORT ssh-rsa $SERVER_KEY_FINGERPRINT" >> ~/.ssh/known_hosts
add your connection host ip to known_hosts then it will not ask for any questions like
Are you sure you want to continue connecting (yes/no)?
or if u want to disable the password asking too, then check this links
http://www.linuxproblem.org/art_9.html
https://www.debian.org/devel/passwordlessssh

Categories