Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I want to write a script which can Shutdown remote Ubuntu system. Actually i want my VM to shutdown safely when i shutdown my main machine on which my VM is installed .
Is there is any of doing this with the help of Sh scripts or script written in any language like Python.
You can run the following command from a remote Linux machine (VM Host):
ssh root#<vm-client-ip> "shutdown -h now"
You will have to input your root password for the remote machine. You can prevent this by adding ssh certificates (good if you are writing a script):
SSH login without password
If you make a script out of this, don't forget to add a delay after the shutdown (e.g. sleep 10) so that the VM will have time to die peacefully.
A complete bash script (untested):
#!/bin/bash
ssh root#<vm-client-ip> "shutdown -h now"
sleep 10
You can use the hypervisor, i.e. the qm script in case of qemu/KVM
qm shutdown 300 && qm wait 300
It shuts down the VM with ID 300, and wait for the VM to stop. See the qm manual for more options.
There are very many ways to turn off a Linux system. The preferred way is to call your window manager's shutdown sequence. If you're using gdm (which you probably are if you're using Ubuntu you want to use:
gnome-session-quit --power-off
If you're using kdm the command is:
kdmctl shutdown
Other ways of shutting down the computer (which may or may not be mostly or completely equivalent, but all require superuser rights) include:
/sbin/init 0
/sbin/halt
/sbin/shutdown -h now
/sbin/poweroff
etc, etc.
The actual command with shuts a system down is shutdown, specifically
$ shutdown -h now
shuts it down now. This needs to be run with superuser privileges on the machine you want to stop.
You can call poweroff from a script, as long as it's running with superuser privileges.
Depending on which virtualization product you are using (e.g. KVM, VirtualBox, VMWare, etc.), there should be a suitable interface you can use.
I suggest you search Google for the name of your chosen virtualisation software + "API". All of the above examples have relevant results that can be called from e.g. Python.
For VirtualBox, check out this link: https://blogs.oracle.com/nike/entry/python_api_to_the_virtualbox
That should give you a SOAP interface which should allow you remote control via e.g. cURL.
Alternatively for the remote aspect, you could setup private key authentication on the server and save your key's passphrase locally (with e.g. Seahorse), which would allow you secure ssh access without the need to enter your password each time.
Related
Closed. This question is not about programming or software development. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 6 months ago.
Improve this question
I am using Paramiko to make a ssh connection to a remote window machine, and then I use paramiko's exec_command(r'python test.py') to run a 'test.py' on the remote machine. What test.py does is simply opening a 'notepad'.
However, when I use exec_command(), and login to the remote machine by Remote Desktop Connection(RDP) to see if the notepad is actually opened. Nothing is opened in the remote machine.
I know my SSH connection is correctly set up and working. But why can't I see the result in RDP, and how can I see the result in RDP?
Paramiko (Python Module) works on the SSHv2 protocol. It provides both client and server functionality. Paramiko module can be used if the SSH server is running on the target machine. The target machines can be Linux or Windows systems. For Linux systems, SSH packages are already available hence we can use them easily. But for Windows systems, the SSH package is not available by default. Hence to enable the SSH server on Windows machine we have to install some extra third-party software.
Using the freeSSHd application, it is possible for a user to set up a secure shell on a Windows machine. It also has a GUI tool for the configuration of both services. Below mentioned are the required steps by steps of getting an SSH server up and running on any user’s Windows client.
Pre-Requirements:
Windows machine (a desktop or a server)
freeSSHd installable
Admin right to open port 22
Installation of freeSSHd:
Download freeSSHd from below mentioned link:
http://www.freesshd.com/?ctt=download
Just double-click the installation file. The user has to look at the below-mentioned points while installing:
User has to generate the Private keys. User will be prompted for this while installation), and
Please it is recommended that freeSSHd should not be started as a system service
How to use freeSSHd:
Just double-click on the freeSSHd desktop icon. A new icon can be seen in the system tray.
The user can see the freeSSHd in the system tray.
Just after right click the system tray icon and select Settings. Users can see a green check next to the SSH server.
By default Telnet server and SSH server is not running on freeSSHd GUI. The user has to click on them to start any required service.
I have used it for the SSH server hence the user has to click on the ‘SSH server option’ on the GUI. freeSSHd doesn’t use AD information, hence the user has to create a new user who can access the machine. Below mentioned are the steps for creating a new user on freeSSHd.
Step1: Open freeSSHd. Then open the freeSSHd settings window.
Step2: Now, click on the Users tab.
Step3: After that, click on Add button.
Now, the user has to fill in all required and necessary details for a new user in the User Properties dialog and then click on the OK button. Using this user, now a secure shell connection can be established for that windows machine.
Conclusion:
And that’s it. Now SSH server will be running on the Windows machine. Using the required user name (which was provided in freeSSHd GUI) user can connect to this windows machine using Secure Shell.
Here is the sample code should be like below:
import paramiko
hostname = "your-hostname"
username = "your-username"
password = "your-password"
cmd = 'your-command'
#SSH Client connection Code:
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname,username=username,password=password)
print "Connected to %s" % hostname
except paramiko.AuthenticationException:
print “Failed to connect to %s due to wrong username/password” %hostname
exit(1)
except:
print “Failed to connect to %s” %hostname
exit(2)
#Execution Command and get feedback:
try:
stdin, stdout, stderr = ssh.exec_command(cmd)
except Exception as e:
print e.message
err = ''.join(stderr.readlines())
out = ''.join(stdout.readlines())
final_output = str(out)+str(err)
print(final_output)
ref: https://www.calsoftinc.com/blogs/2017/02/run-commands-remote-windows-machine-using-python-paramiko-module.html
ref: https://stackoverflow.com/a/48682660/18600126
Good Day
I work for an ISP and we basically manage all our switches and routers via the CLI from a Jumpbox.
I would like to automate some of my work on these devices by writing Python scripts, etc.
However, this Jumpbox (Linux), is quite old and the Python version is old. I cannot add Ansible, Netmiko, etc. Plus I'm not an Admin for that box so can't upgrade it.
My question is, if I set up my own Linux VM with all the required tools, how would I be able to access these routers and switches from my local Linux VM?
I tried setting up a Local/Remote/Dynamic SSH Tunnel to the Jumpbox, but I always end up on the Jumpbox SSH session itself.
You can use the jumpbox as a bastion host. Copy your public keys to both hosts (the jumpbox and the devices) and in your inventory file use the ansible_ssh_common_args option to set it up, like this:
[switches]
switch-01 ansible_host=192.168.0.1 ansible_ssh_common_args='-o ProxyCommand="ssh -W %h:%p -q user#ip-bastion"'
Note: you must be running Ansible version 2.
Best regards.
I'm pulling and pushing to a github repository with a python script. For the github repository, I need to use a ssh key.
If I do this manually before running the script:
eval $(ssh-agent -s)
ssh-add ~/.ssh/myprivkey
everything works fine, the script works. But, after a while, apparently the key expires, and I have to run those 2 cmds again
The thing is, if I do that inside the python script, with os.system(cmd), it doesn't work, it only works if I do that manually
I know this must be a messy way to use the ssh agent, but I honestly don't know how it works, and I just want the script to work, that's all
The script runs once an hour, just in case
While the normal approach would be to run your Python script in a shell where the ssh agent is already running, you can also consider an alternative approach with sshify.py
# This utility will execute the given command (by default, your shell)
# in a subshell, with an ssh-agent process running and your
# private key added to it. When the subshell exits, the ssh-agent
# process is killed.
Consider defining the ssh key path against a host of github.com in your ssh config file as outlined here: https://stackoverflow.com/a/65791491/14648336
If Linux then at this path ~/.ssh/ create a file called config and input something similar to in the above answer:
Host github.com
HostName github.com
User your_user_name
IdentityFile ~/.ssh/your_ssh_priv_key_file_name
This would save the need for starting an agent each time and also prevent the need for custom environment variables if using GitPython (you mention using Python) as referenced in some other SO answers.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So everyday, I need to login to a couple different hosts via ssh and run some maintenance commands there in order for the QA team to be able to test my features.
I want to use a python script to automate such boring tasks. It would be something like:
ssh host1
deploy stuff
logout from host1
ssh host2
restart stuff
logout from host2
ssh host3
check health on stuff
logout from host3
...
It's killing my productivity, and I would like to know if there is something nice, ergonomic and easy to implement that can handle and run commands on ssh sessions programmatically and output a report for me.
Of course I will do the code, I just wanted some suggestions that are not bash scripts (because those are not meant for humans to be read).
You can use the following things programmatically:
For low-level SSH automation - Paramiko
For somewhat higher-level automation - Fabric
Alternatively, if your activities are all around automation of typical sysadmin tasks - have a look at orchestration tools:
Ansible
Saltstack
To give an example in Fabric, define a task to login to a host and run uname -a:
from fabric import *
from fabric.api import *
env.hosts = ['localhost']
def login_to_host_and_run_uname():
run('uname -a')
You can run it as a standalone fabric command:
[none][20:03:32] vlazarenko#alluminium (~/tests)$ fab -f fab.py login_to_host_and_run_uname
[localhost] Executing task 'login_to_host_and_run_uname'
[localhost] run: uname -a
[localhost] Passphrase for private key:
[localhost] out: Darwin alluminium 16.5.0 Darwin Kernel Version 16.5.0: Tue Jan 31 18:57:20 PST 2017; root:xnu-3789.50.195.1.1~1/RELEASE_X86_64 x86_64
[localhost] out:
Done.
Disconnecting from localhost... done.
Fabric also supports easy wrappers for sudo(), caches and works with SSH keys, etc, etc. Allows for easy task parallelisation over multiple hosts and so on.
Could you set up a Cron job or similar on those hosts? That would probably be ideal.
If you don't have the permission to set up Cron jobs, I use a library called paramiko. The code goes like this:
ssh = paramiko.SSHClient()
ssh.connect(host, port=p, timeout=2)
cmd = "ls"
stdin, stdout, stderr = ssh.exec_command(cmd)
for line in stdout.readlines():
print(line)
ssh.close()
If these manual stuffs is too many, then I may look into some server configuration managements like Ansible.
I have done this kinda automation using:
Ansible
Python Fabric
Rake
I want to execute a Python script on several (15+) remote machine using SSH. After invoking the script/command I need to disconnect ssh session and keep the processes running in background for as long as they are required to.
I have used Paramiko and PySSH in past so have no problems using them again. Only thing I need to know is how to disconnect a ssh session in python (since normally local script would wait for each remote machine to complete processing before moving on).
This might work, or something similar:
ssh user#remote.host nohup python scriptname.py &
Basically, have a look at the nohup command.
On Linux machines, you can run the script with 'at'.
echo "python scriptname.py" ¦ at now
If you are going to perform repetitive tasks on many hosts, like for example deploying software and running setup scripts, you should consider using something like Fabric
Fabric is a Python (2.5 or higher) library and command-line tool for
streamlining the use of SSH for application deployment or systems
administration tasks.
It provides a basic suite of operations for executing local or remote
shell commands (normally or via sudo) and uploading/downloading files,
as well as auxiliary functionality such as prompting the running user
for input, or aborting execution.
Typical use involves creating a Python module containing one or more
functions, then executing them via the fab command-line tool.
You can even use tmux in this scenario.
As per the tmux documentation:
tmux is a terminal multiplexer. It lets you switch easily between several programs in one terminal, detach them (they keep running in the background) and reattach them to a different terminal. And do a lot more
From a tmux session, you can run a script, quit the terminal, log in again and check back as it keeps the session until the server restart.
How to configure tmux on a cloud server