def set_ports(name, protocol, iptables_cmd, default): accept_ports = rlinput('{} ports for {}: '.format(protocol, name), default) for p in accept_ports.split(';'): p = p.strip() if not p: continue if '-' in p or ',' in p: sudo(MULTIPORT_CMD.format(iptables_cmd, protocol, p)) else: sudo(TCP_CMD.format(iptables_cmd, protocol, protocol, p))
def check_dpkg(): purge_list = [] with hide('stdout'): for i, line in enumerate(str(run('dpkg -l')).splitlines()): if i < 6: continue if line.startswith(b'ii'): continue line = line.strip() if line.startswith(b'rc'): purge_list.append(line.split()[1]) continue print(line) if purge_list: sudo('aptitude -y purge ' + ' '.join(purge_list))
def sysctl(): netconf = '/etc/sysctl.d/net.conf' buf = StringIO.StringIO(b'''\ net.ipv4.tcp_congestion_control = htcp net.core.rmem_default = 2621440 net.core.rmem_max = 16777216 net.core.wmem_default = 655360 net.core.wmem_max = 16777216 net.ipv4.tcp_rmem = 4096 2621440 16777216 net.ipv4.tcp_wmem = 4096 655360 16777216 ''') put(buf, netconf, use_sudo=True) sudo('chown root.root %s' % netconf) sudo('sysctl -p /etc/sysctl.d/net.conf')
def sysctl(): netconf = '/etc/sysctl.d/net.conf' buf = StringIO.StringIO(b'''\ net.ipv4.tcp_congestion_control = bbr net.core.rmem_default = 2621440 net.core.rmem_max = 16777216 net.core.wmem_default = 655360 net.core.wmem_max = 16777216 net.ipv4.tcp_rmem = 4096 2621440 16777216 net.ipv4.tcp_wmem = 4096 655360 16777216 net.ipv4.tcp_retries2 = 8 ''') put(buf, netconf, use_sudo=True) sudo('chown root.root %s' % netconf) sudo('sysctl -p /etc/sysctl.d/net.conf')
def service(): sudo('ln -sf bash /bin/sh')
def iptables_save(): apt_check_and_install('iptables-persistent') sudo('iptables-save > {}'.format('/etc/iptables/rules.v4')) sudo('ip6tables-save > {}'.format('/etc/iptables/rules.v6')) sudo('service netfilter-persistent restart')
def ip6tables(): with hide('stdout'): rules = sudo('ip6tables -n -v -L INPUT') tcpports = ';'.join(get_port_list(rules, 'tcp')) or '22' udpports = ';'.join(get_port_list(rules, 'udp')) sudo('ip6tables -P INPUT ACCEPT') sudo('ip6tables -F INPUT') sudo('ip6tables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT') sudo('ip6tables -A INPUT -i lo -j ACCEPT') sudo('ip6tables -A INPUT -p ipv6-icmp -j ACCEPT') print('line split by semicolon.') if '22' not in tcpports: print('WARNING: ssh default port not in tcp list,\ this may cause connection broken.') set_ports('ipv6', 'tcp', 'ip6tables', tcpports) set_ports('ipv6', 'udp', 'ip6tables', udpports) sudo('ip6tables -P INPUT DROP')
def apt_check_and_install(name): with settings(warn_only=True): if sudo('dpkg-query -s {}'.format(name)).succeeded: return sudo('aptitude install {}'.format(name))
def chtz_sh(): sudo('echo "Asia/Shanghai" > /etc/timezone') sudo('DEBIAN_FRONTEND=noninteractive dpkg-reconfigure tzdata')
def upgrade(): sudo('aptitude -q=2 update') sudo('aptitude -y full-upgrade') sudo('aptitude clean') sudo('aptitude forget-new')