def hostname(): hostname = socket.getfqdn() form = HostSettingsForm() if not form.is_submitted(): form.hostname.data = hostname if form.validate_on_submit(): new_hostname = form.hostname.data if os.access(HOSTS_FILE, os.W_OK): _sethostname(HOSTS_FILE, hostname, new_hostname) else: flash('Unable to write HOSTS FILE, check permissions', 'error') if os.access(HOSTNAME_FILE, os.W_OK): _sethostname(HOSTNAME_FILE, hostname, new_hostname) else: flash('Unable to write HOSTNAME FILE, check permissions', 'error') with sh.sudo: try: sh.hostname("-b", new_hostname) except sh.ErrorReturnCode_1: flash('Error setting hostname with the hostname command.', 'error') if hasservice: try: sh.service("avahi-daemon", "restart") except sh.ErrorReturnCode_1: flash('Error restarting the avahi-daemon', 'error') return redirect(url_for('settings.host')) return render_template('settings/hostname.html', hostname=hostname, form=form, active="hostname")
def configure_mta(mail_server_address, goodcrypto_listen_port, mta_listen_port): ''' Configure postfix to work with the main MTA. ''' try: new_configuration = False if not isinstance(mail_server_address, str): mail_server_address = mail_server_address.decode() if configure_main(mail_server_address, mta_listen_port): new_configuration = True log.write_and_flush('new main config') if configure_master(goodcrypto_listen_port): new_configuration = True log.write_and_flush('new master config') if new_configuration: # restart postfix with the new settings log.write_and_flush('restarting postfix') sh.service('postfix', 'restart') log.write_and_flush('postfix restarted') except Exception: log.write_and_flush('EXCEPTION - see syr.exception.log') record_exception() raise return new_configuration
def setupPhpFpm(username): fpmConfFile = '%s/%s.pool.conf'%(PHP_INI_DIR,domain) phpFpmTemplate = open("pool.conf.template").read() phpFpmTemplate = phpFpmTemplate.replace("@@USER@@", username) phpFpmConf = open(fpmConfFile, "w") phpFpmConf.write(phpFpmTemplate) phpFpmConf.close() sh.service("php5-fpm","restart")
def setupPhpFpm(username): fpmConfFile = '%s/%s.pool.conf' % (PHP_INI_DIR, domain) phpFpmTemplate = open("pool.conf.template").read() phpFpmTemplate = phpFpmTemplate.replace("@@USER@@", username) phpFpmConf = open(fpmConfFile, "w") phpFpmConf.write(phpFpmTemplate) phpFpmConf.close() sh.service("php5-fpm", "restart")
def allowSSH(): lines = [] with open("/etc/ssh/sshd_config", "r")as origFile: contents = origFile.read() contents = contents.replace("PasswordAuthentication no", "PasswordAuthentication yes \n") # contents = contents.replace("#PubkeyAuthentication", "PubkeyAuthentication") with (open("/etc/ssh/sshd_config", "w")) as newFile: newFile.write(contents) # os.system("service sshd restart") service("sshd", "restart")
def installAmbariAgent(ambariServer): ambariAgentConfigFile = "/etc/ambari-agent/conf/ambari-agent.ini" PackageManager.install("ambari-agent") lines = [] with open(ambariAgentConfigFile, "r")as origFile: contents = origFile.read() contents = contents.replace("localhost", ambariServer) with (open(ambariAgentConfigFile, "w")) as newFile: newFile.write(contents) # os.system("service ambari-agent start") service("ambari-agent", "start")
def setupNginx(domain,username,confTemplate,sitePublic,siteLogs): nginxSitesAvailable = '%s/%s'%(NGINX_CONFIG,domain) nginxEnabled = '%s/%s'%(NGINX_SITES_ENABLED,domain) nginxTemplate = open(confTemplate).read() nginxTemplate = nginxTemplate.replace("@@HOSTNAME@@", domain) nginxTemplate = nginxTemplate.replace("@@PATH@@", sitePublic) nginxTemplate = nginxTemplate.replace("@@LOG_PATH@@", siteLogs) nginxTemplate = nginxTemplate.replace("@@SOCKET@@", username) nginxConf = open(nginxSitesAvailable, "w") nginxConf.write(nginxTemplate) nginxConf.close() sh.chmod('600', nginxSitesAvailable) os.symlink(nginxSitesAvailable, nginxEnabled) sh.service("nginx","restart")
def setupNginx(domain, username, confTemplate, sitePublic, siteLogs): nginxSitesAvailable = '%s/%s' % (NGINX_CONFIG, domain) nginxEnabled = '%s/%s' % (NGINX_SITES_ENABLED, domain) nginxTemplate = open(confTemplate).read() nginxTemplate = nginxTemplate.replace("@@HOSTNAME@@", domain) nginxTemplate = nginxTemplate.replace("@@PATH@@", sitePublic) nginxTemplate = nginxTemplate.replace("@@LOG_PATH@@", siteLogs) nginxTemplate = nginxTemplate.replace("@@SOCKET@@", username) nginxConf = open(nginxSitesAvailable, "w") nginxConf.write(nginxTemplate) nginxConf.close() sh.chmod('600', nginxSitesAvailable) os.symlink(nginxSitesAvailable, nginxEnabled) sh.service("nginx", "restart")
def configure(domain): ''' Configure DKIM for the local domain. >>> # save the original conf and host files >>> from shutil import copy2 >>> copy2('/etc/opendkim/opendkimhosts', '/etc/opendkim/opendkimhosts.local') >>> copy2('/etc/opendkim.conf', '/etc/opendkim/opendkim.conf.local') >>> # set up template files >>> copy2('/etc/opendkim/opendkimhosts.template', '/etc/opendkim/opendkimhosts') >>> copy2('/etc/opendkim/opendkim.conf.template', '/etc/opendkim.conf') >>> configure('goodcrypto.remote') True >>> os.remove('/etc/opendkim/goodcrypto.remote/dkim.public.key') >>> os.remove('/etc/opendkim/goodcrypto.remote/dkim.private.key') >>> os.rmdir('/etc/opendkim/goodcrypto.remote') >>> # restore the conf and hosts files >>> copy2('/etc/opendkim/opendkimhosts.local', '/etc/opendkim/opendkimhosts') >>> copy2('/etc/opendkim/opendkim.conf.local', '/etc/opendkim.conf') >>> results = sh.service('opendkim', 'restart') ''' try: new_configuration = False if domain is None: log.write_and_flush('cannot config dkim without a domain defined') else: if configure_conf(domain): new_configuration = True if configure_hosts(domain): new_configuration = True if configure_key(domain): new_configuration = True if new_configuration: # restart opendkim with the new settings sh.service('opendkim', 'restart') log.write_and_flush('opendkim restarted') except Exception: record_exception() raise return new_configuration
def stop_wireless(): ''' Try official ways to stop wireless such as nmcli and rfkill. These often leave the service enabled, or the service is re-enabled on boot. To do: check rmcomm piconets ''' if not sh.which('nm'): sh.aptitude('install', 'nmcli') assert sh.which('nm') if not sh.which('service'): service_path = '/usr/local/sbin/service' with open(service_path, 'w') as service_file: service_file.write(service_script_text) os.chmod(service_path, 0o755) assert sh.which('service') try: sh.nmcli('nm', 'wifi', 'off') sh.nmcli('nm', 'wwan', 'off') except: pass # rfkill block all try: #if not sh.which ('rfkill'): # sh.aptitude('install', 'rfkill') #assert sh.which ('rfkill') sh.rfkill('block', 'all') except: # some variants of linux don't have /dev/rfkill, # so there's no program rfkill pass # /etc/init.d/bluetooth stop try: sh.service(Bluetooth, 'stop') except: try: sh.service(Bluetooth+'-unused', 'stop') except: pass
def status(self, name=''): """WIP!""" raise NotImplementedError() super(SysV, self).status(name=name) try: sh.service(name, 'status') except sh.CommandNotFound: self.lgr.warning('service command unavailable. Trying to run ' 'script directly.') try: service = sh.Command('/etc/init.d/{0}'.format(self.name)) except sh.CommandNotFound as ex: self.lgr.error('Command not found: {0}'.format(str(ex))) sys.exit() svc_info = self._parse_service_info(service.status()) self.services['services'] = svc_info return self.services
def configure_mailname(domain): ''' Configure mailname ''' if not isinstance(domain, str): domain = domain.decode() new_configuration, new_lines = mailname_needs_configuration(domain) if new_configuration: with open(MAILNAME_FILE, 'wt') as output_file: output_file.write(''.join(new_lines)) log.write_and_flush('updated mailname') # restart postfix with the new settings sh.service('postfix', 'restart') log.write_and_flush('postfix restarted') return new_configuration
def main(): if not sh.which('pip3'): print('installing pip3') sh.apt_get("install", "python3-pip", "-y") if not sh.which('pip3'): print('pip3 install failed.') return print('pip3 installed') print('installing python package') print('flask.') sh.pip3("install", "flask") print('rsa.') sh.pip3("install", "rsa") if not sh.which('supervisorctl'): print('installing supervisor') sh.apt_get("install", "supervisor", "-y") if not sh.which('supervisorctl'): print('supervisor install failed') return print('supervisor installed') ans = input('Do you want to copy files to /root? [y/N]') if ans == 'Y' or ans == 'y': print('copying files to /root/Adence') sh.cp('../Adence', '-R', '/root') print('config supervisor') cmd = r'''[program:Adence] command=python3 /root/Adence/main.py autostart=true autorestart=true stderr_logfile=/var/log/Adence.err.log stdout_logfile=/var/log/Adence.out.log ''' with open('/etc/supervisor/conf.d/Adence.conf', 'w') as fp: fp.write(cmd) sh.service('supervisor', 'restart') print('done. you can visit http://localhost:9000 now.') else: print('environment settled.you need to run the main.py manually')
def osConfig(): print "OS COnfigs" chkconfig("iptables", "off") chkconfig("ip6tables", "off") service("iptables", "stop") service("ip6tables", "stop") service("ambari-agent", "start") seLinux = "/etc/selinux/config" with open(seLinux, "r")as origFile: contents = origFile.read() contents = contents.replace("SELINUX=enforcing", "SELINUX=disabled") with (open(seLinux, "w")) as newFile: newFile.write(contents) os.system("echo 0 > /selinux/enforce") service("ambari-agent", "start")
def __init_monit_config(self, enable=False, target_host="8.8.8.8", iface="", cycles=1): if enable is False: rm("-rf", "/etc/monit/conf.d/keepalive") service("monit", "restart") return ifacecmd = "" if iface == "" or iface is None \ else "-I {}".format(iface) config = """check program ping-test with path "/bin/ping {target_host} {ifacecmd} -c 3 -W 20" if status != 0 then exec "/bin/bash -c '/usr/sbin/cell_mgmt power_off force && /bin/sleep 5 && /sbin/reboot -i -f -d'" every {cycles} cycles """ # noqa with open("/etc/monit/conf.d/keepalive", "w") as f: f.write( config.format(target_host=target_host, ifacecmd=ifacecmd, cycles=cycles)) service("monit", "restart")
def patch_sshd_config(patch_param): from . import BACKUPS_PATH default_value, safe_value = SSHD_CONFIG_PARAMS_INFO[patch_param] if not os.path.isfile(SSHD_CONFIG_PATH): logger.error('{} not found'.format(SSHD_CONFIG_PATH)) return try: from sh import sshd, service except ImportError: logger.exception('sshd or service executable not found') return safe_value_string = '\n# Added by wott-agent on {}\n{} {}\n'.format( time.ctime(), patch_param, safe_value) backup_filename = os.path.join(BACKUPS_PATH, 'sshd_config.' + str(int(time.time()))) replaced = False with open(SSHD_CONFIG_PATH, 'r+') as sshd_config: safe = False lines = sshd_config.readlines() patched_lines = [] for line in lines: patched_lines.append(line) line = line.strip() if not line or line[0] == '#': # skip empty lines and comments continue line_split = line.split(maxsplit=1) if len(line_split) != 2: continue param, value = line_split value = value.strip('"') if param == patch_param: if value != safe_value: logger.info('{}: replacing "{}" with "{}"'.format( param, value, safe_value)) patched_lines[-1] = safe_value_string replaced = True safe = False else: safe = True if not replaced and not safe and default_value != safe_value: logger.info('{}: replacing default "{}" with "{}"'.format( patch_param, default_value, safe_value)) patched_lines.append(safe_value_string) replaced = True if replaced: if patch_param == 'PasswordAuthentication': if not confirmation( "Warning: Before you disable password authentication, make sure that you have generated " "and installed your SSH keys on this server. Failure to do so will result in that you " "will be locked out. I have have my SSH key(s) installed:" ): return logger.info('Backing up {} as {}'.format(SSHD_CONFIG_PATH, backup_filename)) shutil.copy(SSHD_CONFIG_PATH, backup_filename) logger.info('Writing {}'.format(SSHD_CONFIG_PATH)) sshd_config.seek(0, 0) sshd_config.truncate() sshd_config.writelines(patched_lines) else: logger.info('Nothing to patch.') return try: sshd('-t') except ErrorReturnCode_255 as e: if e.stderr.startswith(SSHD_CONFIG_PATH.encode()): logger.exception('{} is invalid. Restoring from backup.'.format( SSHD_CONFIG_PATH)) shutil.copy(backup_filename, SSHD_CONFIG_PATH) else: logger.exception('something went wrong') return try: service_name = 'ssh' if is_debian() else 'sshd' service([service_name, 'reload']) except ErrorReturnCode_1: logger.exception('failed to reload sshd.') else: logger.info('sshd reloaded.')
def _reload_server(self): service('nginx', 'reload', _bg=True, silent=True)
def status(self): try: sh.service('scst', 'status') return True except: return False
def start(self): return sh.service("scst", "start")
def status(self): try: sh.service("scst", "status") return True except: return False
def start_nginx(): r = sh.service("nginx", "start", _ok_code=[1, 2, 3]) if r.exit_code == 0: print "start success" else: print "start failed"
def start(self): return sh.service('scst', 'start')
def service(name, action='status'): return sh.service(name, action)
def configure_ethernet_device(device): form = EthernetConfigureForm() device_map = None dhcp = True if os.access(NETWORK_FILE, os.W_OK): device_map = _parse_network_file() else: flash(NETWORK_FILE + ' is not writable!', 'error') return redirect(url_for('settings.host')) properties = _get_ethernet_properties(device, device_map) addresses = netifaces.ifaddresses(device) ipv4 = addresses[netifaces.AF_INET] print "Device map:\n" print device_map #first address and gateway ip_address = ipv4[0]['addr'] subnet_mask = ipv4[0]['netmask'] gateways = netifaces.gateways() gateway = gateways['default'][netifaces.AF_INET] default_gateway = gateway[0] if not form.is_submitted(): form.ip_address.data = ip_address form.gateway.data = default_gateway form.netmask.data = subnet_mask if not properties: if device == 'lo' or device == 'lo0': flash('Unable to configure loopback device!', 'error') return redirect(url_for('settings.host')) flash('Device ' + device + ' not found in ' + NETWORK_FILE + ' you should use your OS tools to configure your network.', 'error') #uncomment this return before release # return redirect(url_for('settings.host')) else: print properties for s in properties: if 'loopback' in s: flash('Unable to configure loopback device!', 'error') return redirect(url_for('settings.host')) if 'static' in s: form.connection_type.data = 'static' dhcp = False if 'dhcp' in s: form.connection_type.data = 'dhcp' if form.validate_on_submit(): if form.connection_type.data == 'static': dhcp = False else: dhcp = True #substitute values in the device_map, write the file and restart networking with sh.sudo: try: sh.service("networking restart") except sh.ErrorReturnCode_1: flash('Unable to restart networking. Please try manually.', 'error') form.ethernet_device.data = device form.ethernet_device.data = device return render_template('settings/configure_ethernet_device.html', form=form, device=device, active="network settings")