Fabric - How to supply ssh password dynamically - python

I am trying to use Fabric ,Django and Celery together to do operations on a remote host.
And in my case the remote host is going to be dynamic.
I guess the use of Django and Celery is irrelevant , the question can be narrowed down to
how to supply SSH password dynamically while using Fabric alone.
I found this piece of code which shows how to do this with Django and Celery.
from fabric.api import hosts
from celery import task
#task()
def remote_celery_task():
username, host = get_host_details()
host_string = "%s#%s" % (username, host)
#hosts(host_string)
def fab_task():
run("ls")
execute(fab_task)
But what it doesnt tell is how to dynamically pass SSH passwords to Fabric.
I understand that supplying password this way isnt good security wise, but I am willing to sacrifice security at the moment.
Update
I got it working when I changed the code to
#hosts(host_string)
def my_fab_task():
env.password = testhost.SSH_password # is this the correct way ? its working for me
run("ls")

Skip worrying about the password and just do ssh keygens. Share the keys between the hosts you will be connecting to and you can do passwordless ssh operations on the remote hosts.

Related

how to check service running on other server with python

I have a problem with checking my service on other windows or Linux servers.
My problem is that I have to make a request from one server to the other servers and check if the vital services of those servers are active or disabled.
I wrote Python code to check for services, which only works on a local system.
import psutil
def getService(name):
service = None
try:
service = psutil.win_service_get(name)
service = service.as_dict()
except Exception as ex:
print(str(ex))
return service
service = getService('LanmanServer')
if service:
print("service found")
else:
print("service not found")
if service and service['status'] == 'running':
print("service is running")
else:
print("service is not running")
Does this code have this feature?
Or suggest another code؟
I have reviewed suggestions such as using server agents (influx, ...), which are not working for my needs.
You can use the following code for your service. i think these codes will help you
in your problem.
ip = your_ip
server_user = your_serviceuser
server_pass = your_pass
command = f"net use \\\\{ip} {server_pass} /USER:{server_user}"
os.system(command)
command = f"SC \\\\{ip} query SQLSERVERAGENT"
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output, err = process.communicate()
output = str(str(str(str(output)[2:-1].replace(' ', '')).replace('\\t', '')).replace('\\r', '')).split('\\n')
if output[3] != 'STATE:4RUNNING':
print("service is running...")
As far as I know, psutil can only be used for gathering information about local processes, and is not suitable for retrieving information about processes running on other hosts. If you want to check whether or not a process is running on another host, there are many ways to approach this problem, and the solution depends on how deep you want to go (or need to go), and what your local situation is. From the top of my head, here are some ideas:
If you are only dealing with network services with exposed ports:
A very simple solution would involve using a script and a port scanner (nmap); if a port that a service is listening behind, is open, then we can assume that the service is running. Run the script every once in a while to check up on the services, and do your thing.
If you want to stay in Python, you can achieve the same end result by using Python's socket module to try and connect to a given host and port to determine whether or not the port that a service is listening behind, is open.
A Python package or tool for monitoring network services on other hosts like this probably already exists.
If you want more information and need to go deeper, or you want to check up on local services, your solution will have to involve a local monitor process on each host, and connecting to that process to gather information.
You can use your code to implement a server that lets clients connect to it, to check up on the services running on that host. (Check the socket module's official documentation for examples on how to implement clients and servers.)
Here's the big thing though. Based on your question and how it was asked, I would assume that you do not have the experience nor the insight to implement this in a secure way yet. If you're using this for a simple hobby/student project, roll out your own solution, and learn. Otherwise, I would recommend that you check out an existing solution like Nagios, and follow the security recommendations very closely.

python script using fabric to remote execute is hanging at connection?

I have a short python script (eventually to be larger) that is remote executing a 'pwd' command on the remote host. I am just testing to connect to the host using SSH keys (yes these are set up correctly). What i have so far seems to work, but it sort of just hangs there in the IDLE window...does not error out, but also if i check the host last login date, it doesn't match when i executed the script. Is there a way to have the output show (similar to expect, so i can see if i am actually even logging in).
Tried to use password instead, same exact behavior.
#!/usr/bin/python
from fabric import Connection
sshConnection = Connection(
host = 'hostname.com',
user='myuser',
connect_kwargs={
"key_filename":r'C:\Users\user\Desktop\id_rsa',
},
)
sshConnection.run('pwd')
close()
basically getting this in the IDLE window
>
RESTART: /PATH/TO/SCRIPT/ON/WINDOWS/LAPTOP/script.py
|
I advise you to use fabric2.4.0 and Python 3
from fabric import Connection as connection, task
#task
def deploy(ctx):
with connection(host=host, user=user) as c:
c.run('pwd')
Put the code above in a file called fabfile.py and you run it from your command line
fab deploy

Passwordless SSH using paramiko

Issue : I'm a noob with Paramiko, trying to run some commands from a python script (on personal machine) on a remote server. The remote server doesn't need a password to connect to.
For example, if I do
root#[IPaddress] on my Mac, I'm successfully able to connect to the remote server via MacbookPro terminal.
However, I'm trying to do this inside a Python script using Paramiko, and no matter what I do, I get an Authentication error or No Authentication methods available.
I went through Paramiko AuthenticationException issue but the answers there are vague for me to implement without significant experience with Paramiko. Help?
This is my code:
import paramiko
import os
from paramiko import SSHClient
#Borrowed from the linked post
class SSHClient_noauth(SSHClient):
def _auth(self, username, *args):
self._transport.auth_none(username)
return
#How do I implement?
ssh = SSHClient()
sshc = SSHClient_noauth()._auth(username="root") #Where's the ssh obj passed?
sshc.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshc.connect("10.xxx.xxx.xxx")
Well, not to let the negative vote bog me down.
Tried doing sshc.connect(remoteIP, username=username, password="") and it worked. In case someone has been stuck for over an hour or two trying to get this working, especially for work, you might want to try putting in a "" instead of None.

Python. Need to be sure the connection is made from the local machine?

Imagine you have a HTTP server on your local machine, this is a typical Python/Twisted application. This server is used to access your local data, server is used just as a GUI interface. So user can use his web browser or special application ( acts like a web browser ) to access his local data.
Now you want to be sure that only local user who physically sit near this machine get access to the HTTP server.
Also I will have FTP server and it must be protected the same way too.
At the moment I am running such code for my HTTP server:
class LocalSite(server.Site):
def buildProtocol(self, addr):
if addr.host != '127.0.0.1':
print 'WARNING connection from ' + str(addr)
return None
try:
res = server.Site.buildProtocol(self, addr)
except:
res = None
return res
So I am just check the IP address at the moment and I am not sure this is enough.
Is there any ways to emulate local IP from remote machine.?
Well, If a bad guy get access over my OS I have no way to protect - but this is not my deal. My firewall and antivirus should care about this, right?
Anyway, I would like to listen any extra ideas about increase security of such HTTP server.
May be we can use MAC address to verify connection.?
Check the processes on local machine and detect which is actually executes connection?
We can use HTTPS, but in my understanding this acts in opposite direction: this is for user to trust to the server, not server to trust to the user.
Using CAPTCHA is a kind of solution. But I do not like this at all (it strains users) and this will not work for FTP server.
I am also use random port number every time application starts.
The type of internet connection is not defined - this is a p2p application. Any user in the WEB can use my software and it must be protected against remote access.
I believe the way you handled it is good enough. About it being cross-platform, I believe it is as Windows(starting from windows 7) too maps localhost to 127.0.0.1 but for previous versions, you have to define localhost in the main hosts file.

Fabric authentication with kerberos

I'm trying to write a fabric function that puts a script on a remote host and runs it as root. I don't have the root password to login to the machine, nor am I a sudoer, but I do have a root principle in kerberos. Typically, I can connect to a machine as root with the following:
kinit username/root
(enter root principle pass)
ssh root#host
Connecting in this manner I'm not prompted for a password when ssh'ing to the host.
So I want to emulate this process using fabric. To do so I assumed the following,
kinit user/root
fab task1 task2 --user=root
Unfortunately fabric prompts me for a password, while I do not have the root password, I can't supply this. Fabric will not let me pass a null for the password as far as I can tell. Any ideas?
Looks like Fabric doesn't support Kerberos authentication. If I remember correctly paramiko library doesn't support it either and Fabric uses paramiko (not sure), so it doesn't have corresponding support.
You should go and ask here:
http://docs.fabfile.org/en/1.4.1/index.html#getting-help
May be use IRC channel so as to get quick response.
Regards,
There is an open pull request for support of Kerberos in Fabric and it looks like it's working and is almost ready to be merged:
https://github.com/fabric/fabric/pull/1261
Fabric 2.6.0 supports gssapi through paramiko (03/2022). You'll also need to install python-gssapi.
You just need to pass connect_kwargs to __init__():
class GSSConnection(Connection):
def __init__(self, host):
connect_kwargs = dict(
gss_auth=True,
gss_deleg_creds=True,
gss_kex=True,
)
super().__init__(host, connect_kwargs=connect_kwargs)

Categories

Resources