Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Restart Apache web server on a remote host when getting a ConnectionError
# Python imports
import requests
from requests import exceptions
import paramiko
import os
import time
# Note: Remember to add environment variable PASSWORD in bash_profile and source it.
# Local variables
host = "" # IP address of host
url = "http://{0}/say_my_name".format(host)
response = None
retry_attempts = 3
#command to execute on the remote server
command = "sudo service apache2 restart"
while response is None and retry_attempts > 0:
response = requests.get(url=url)
except exceptions.ConnectionError as e:
if "PASSWORD" not in os.environ:
print("password not found, exiting")
# Create SSH client and set Auto Add policy to add host to ~/.ssh/known_hosts file
ssh = paramiko.SSHClient()
#Connect to host
ssh.connect(hostname=host, username="srikkanth", password=os.environ["PASSWORD"])
# Invoke a separate shell to execute command
shell = ssh.invoke_shell()
shell.send(command + "\n")
# Wait if necessary
# Get the console messages on the screen and print them. This can be used for verifying output as well using regex
rec_buffer = shell.recv(1024)
retry_attempts -= 1
# At this point apache should be up unless something really bad has happened, in which case, check out the apache error log.
# We should have got a response other than None if apache is up.
if response.status_code == 200:
print("Successfully displayed the name")
# Have an assert to fail the test instead of just printing to console.
assert response.status_code == 200, "Response code expected - 200, got {0}\n\nResponse content\n\n{1}".format(
response.status_code, response.content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.