{"id":245,"date":"2023-08-23T16:45:09","date_gmt":"2023-08-23T16:45:09","guid":{"rendered":"http:\/\/77interactive.com\/?p=245"},"modified":"2023-09-13T14:55:30","modified_gmt":"2023-09-13T14:55:30","slug":"linux-configuration-script-in-python","status":"publish","type":"post","link":"http:\/\/77interactive.com\/?p=245","title":{"rendered":"Linux Configuration Script in Python"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Verifying Linux Setting in Python<\/h2>\n\n\n\n<p>The following Python script checks several Linux settings. Results of the check are written to the console. If the results are within the desired ranges and values, the results are displayed in green. If the values are outside of the desired ragnes, results are displayed in red.<\/p>\n\n\n\n<p>All results are written to a json outfile located at \/tmp\/linuxverification.json<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><em>Python code<\/em><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import subprocess\r\nimport socket\r\nimport os\r\nimport json\r\nimport platform\r\n\r\ndef get_value_from_sys_path(path):\r\n    try:\r\n        with open(path, 'r') as f:\r\n            return f.read().strip()\r\n    except Exception:\r\n        return None\r\n\r\n# Check function for exact values\r\ndef check_value_exact(value, target):\r\n    return str(value) == str(target)\r\n\r\n# Check function for in_range column\r\n# If the value is in range, then return True\r\ndef check_value_in_range(value, check_func):\r\n    if value is None:\r\n        return False\r\n    return check_func(value)\r\n\r\n# Get system total memory\r\ndef get_memory_info():\r\n    with open(\"\/proc\/meminfo\", \"r\") as f:\r\n        for line in f.readlines():\r\n            if \"MemTotal\" in line:\r\n                memory_kb = int(line.split()&#91;1])\r\n                return memory_kb \/ (1024 * 1024)  # Convert KB to GB\r\n\r\n# Checks the Transparent Huge Pages status\r\n# The status can be one of the following:\r\n# always, madvise, never\r\ndef check_thp_status():\r\n    path = \"\/sys\/kernel\/mm\/transparent_hugepage\/enabled\"\r\n    thp_value = get_value_from_sys_path(path)\r\n    if \"&#91;never]\" in thp_value:\r\n        return (True, \"&#91;never]\")\r\n    elif \"&#91;always]\" in thp_value:\r\n        return (False, \"&#91;always]\")\r\n    elif \"&#91;madvise]\" in thp_value:\r\n        return (False, \"&#91;madvise]\")\r\n    else:\r\n        return (None, \"Unknown\")\r\n\r\n# Get network adapters and their IP addresses\r\ndef get_ip_addresses():\r\n    try:\r\n        output = subprocess.check_output(&#91;\"hostname\", \"--all-ip-addresses\"]).decode('utf-8').strip()\r\n        return output.split()\r\n    except Exception as e:\r\n        print(f\"Error fetching IP addresses: {e}\")\r\n        return &#91;]\r\n\r\n# Print colored text to console based acceptable ranges\r\ndef print_colored(text, color):\r\n    endc = '\\033&#91;0m'\r\n    print(f\"{color}{text}{endc}\")\r\n\r\ndef main():\r\n    settings = {\r\n        \"vm.swappiness\": {\r\n            \"path\": \"\/proc\/sys\/vm\/swappiness\",\r\n            \"acceptable\": \"10 or less\",\r\n            \"check_func\": lambda x: int(x) &lt;= 10\r\n        },\r\n        \"vm.dirty_ratio\": {\r\n            \"path\": \"\/proc\/sys\/vm\/dirty_ratio\",\r\n            \"acceptable\": \"less than 15\",\r\n            \"check_func\": lambda x: int(x) &lt; 15\r\n        },\r\n        \"vm.dirty_background_ratio\": {\r\n            \"path\": \"\/proc\/sys\/vm\/dirty_background_ratio\",\r\n            \"acceptable\": \"5 or less\",\r\n            \"check_func\": lambda x: int(x) &lt;= 5\r\n        },\r\n        \"net.core.somaxconn\": {\r\n            \"path\": \"\/proc\/sys\/net\/core\/somaxconn\",\r\n            \"acceptable\": \"4096\",\r\n            \"check_func\": lambda x: check_value_exact(x, 4096)\r\n        },\r\n        'net.ipv4.tcp_fin_timeout': {\r\n            'path': '\/proc\/sys\/net\/ipv4\/tcp_fin_timeout',\r\n            'acceptable': 30,\r\n            'check_func': lambda x: check_value_exact(x, 30)\r\n        },\r\n        'net.ipv4.tcp_keepalive_intvl': {\r\n            'path': \"\/proc\/sys\/net\/ipv4\/tcp_keepalive_intvl\",\r\n            'acceptable': 30,\r\n            'check_func': lambda x: check_value_exact(x, 30)\r\n        },\r\n        'net.ipv4.tcp_keepalive_time': {\r\n            'path': \"\/proc\/sys\/net\/ipv4\/tcp_keepalive_time\",\r\n            'acceptable': 120,\r\n            'check_func': lambda x: check_value_exact(x, 120)\r\n        },\r\n        'net.ipv4.tcp_max_syn_backlog': {\r\n            'path': \"\/proc\/sys\/net\/ipv4\/tcp_max_syn_backlog\",\r\n            'acceptable': 4096,\r\n            'check_func': lambda x: check_value_exact(x, 4096)\r\n        },\r\n        'net.ipv4.tcp_keepalive_probes': {\r\n            'path': \"\/proc\/sys\/net\/ipv4\/tcp_keepalive_probes\",\r\n            'acceptable': 6,\r\n            'check_func': lambda x: check_value_exact(x, 6)\r\n        }\r\n    }\r\n\r\n    # Add the Server specs to the results dictionary\r\n    # which will be used in the output file.\r\n    results = {\r\n        \"Server Name\": socket.gethostname(),\r\n        \"Processor Information\": platform.processor(),\r\n        \"Number of Processor Cores\": os.cpu_count(),\r\n        \"Total Memory (GB)\": get_memory_info(),\r\n        \"IP Addresses\": get_ip_addresses()\r\n    }\r\n\r\n    # Display the server specs on the terminal\r\n    print(f\"Server Name: {results&#91;'Server Name']}\")\r\n    print(f\"Processor Information: {results&#91;'Processor Information']}\")\r\n    print(f\"Number of Processor Cores: {results&#91;'Number of Processor Cores']}\")\r\n    print(f\"Total Memory (GB): {results&#91;'Total Memory (GB)']:.2f}\")\r\n    for ip in results&#91;'IP Addresses']:\r\n        print(f\"IP Address: {ip}\")\r\n    print(\"-\" * 91)\r\n\r\n    # Print settings table header\r\n    print(\"{:&lt;30} {:&lt;30} {:&lt;20} {:&lt;10}\".format(\"Setting\", \"Acceptable Ranges\", \"Current Value\", \"In Range\"))\r\n    print(\"-\" * 91)\r\n\r\n    # Build the output dictionary\r\n    output = {}\r\n\r\n    # Loop over the settings dictionary\r\n    # Determine the current value of the setting and if the\r\n    # value is in the acceptable range. If so, then print\r\n    # the setting in green, otherwise print it in red.\r\n    # We also add the setting to the output dictionary\r\n    for setting_name, setting_details in settings.items():\r\n        value = get_value_from_sys_path(setting_details&#91;\"path\"])\r\n        in_range = check_value_in_range(value, setting_details&#91;\"check_func\"])\r\n        \r\n        print_colored(\r\n            \"{:&lt;30} {:&lt;30} {:&lt;20} {:&lt;10}\".format(\r\n                setting_name, \r\n                str(setting_details&#91;\"acceptable\"]), \r\n                str(value),\r\n                str(in_range)\r\n            ),\r\n            \"\\033&#91;92m\" if in_range else \"\\033&#91;91m\"\r\n        )\r\n\r\n        # Add the setting to the output dictionary\r\n        # which will be used in the out file\r\n        output&#91;setting_name] = {\r\n            \"current_value\": value,\r\n            \"acceptable_values\": setting_details&#91;\"acceptable\"],\r\n            \"in_range\": in_range\r\n        }\r\n\r\n    # Add the settings to the results dictionary\r\n    results&#91;\"Settings\"] = output\r\n\r\n    # Save results to a JSON file\r\n    with open(\"\/tmp\/linuxverification.json\", \"w\") as file:\r\n        json.dump(results, file, indent=4)\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Verifying Linux Setting in Python The following Python script checks several Linux settings. Results of the check are written to the console. If the results are within the desired ranges and values, the results are displayed in green. If the values are outside of the desired ragnes, results are displayed in red. All results are [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":246,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11,2],"tags":[42,5,3],"class_list":["post-245","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-mongodb","category-python","tag-linux","tag-mongodb","tag-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Linux Configuration Script in Python - 77 Interactive<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"http:\/\/77interactive.com\/?p=245\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Linux Configuration Script in Python - 77 Interactive\" \/>\n<meta property=\"og:description\" content=\"Verifying Linux Setting in Python The following Python script checks several Linux settings. Results of the check are written to the console. If the results are within the desired ranges and values, the results are displayed in green. If the values are outside of the desired ragnes, results are displayed in red. All results are [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"http:\/\/77interactive.com\/?p=245\" \/>\n<meta property=\"og:site_name\" content=\"77 Interactive\" \/>\n<meta property=\"article:published_time\" content=\"2023-08-23T16:45:09+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-09-13T14:55:30+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/77interactive.com\/wp-content\/uploads\/2023\/08\/linux-config.jpeg\" \/>\n\t<meta property=\"og:image:width\" content=\"512\" \/>\n\t<meta property=\"og:image:height\" content=\"512\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Rudy\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Rudy\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"http:\/\/77interactive.com\/?p=245#article\",\"isPartOf\":{\"@id\":\"http:\/\/77interactive.com\/?p=245\"},\"author\":{\"name\":\"Rudy\",\"@id\":\"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9\"},\"headline\":\"Linux Configuration Script in Python\",\"datePublished\":\"2023-08-23T16:45:09+00:00\",\"dateModified\":\"2023-09-13T14:55:30+00:00\",\"mainEntityOfPage\":{\"@id\":\"http:\/\/77interactive.com\/?p=245\"},\"wordCount\":72,\"image\":{\"@id\":\"http:\/\/77interactive.com\/?p=245#primaryimage\"},\"thumbnailUrl\":\"http:\/\/77interactive.com\/wp-content\/uploads\/2023\/08\/linux-config.jpeg\",\"keywords\":[\"Linux\",\"mongodb\",\"python\"],\"articleSection\":[\"mongodb\",\"Python\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"http:\/\/77interactive.com\/?p=245\",\"url\":\"http:\/\/77interactive.com\/?p=245\",\"name\":\"Linux Configuration Script in Python - 77 Interactive\",\"isPartOf\":{\"@id\":\"http:\/\/77interactive.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"http:\/\/77interactive.com\/?p=245#primaryimage\"},\"image\":{\"@id\":\"http:\/\/77interactive.com\/?p=245#primaryimage\"},\"thumbnailUrl\":\"http:\/\/77interactive.com\/wp-content\/uploads\/2023\/08\/linux-config.jpeg\",\"datePublished\":\"2023-08-23T16:45:09+00:00\",\"dateModified\":\"2023-09-13T14:55:30+00:00\",\"author\":{\"@id\":\"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9\"},\"breadcrumb\":{\"@id\":\"http:\/\/77interactive.com\/?p=245#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"http:\/\/77interactive.com\/?p=245\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/77interactive.com\/?p=245#primaryimage\",\"url\":\"http:\/\/77interactive.com\/wp-content\/uploads\/2023\/08\/linux-config.jpeg\",\"contentUrl\":\"http:\/\/77interactive.com\/wp-content\/uploads\/2023\/08\/linux-config.jpeg\",\"width\":512,\"height\":512,\"caption\":\"Linux Configuration\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"http:\/\/77interactive.com\/?p=245#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/77interactive.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Linux Configuration Script in Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/77interactive.com\/#website\",\"url\":\"http:\/\/77interactive.com\/\",\"name\":\"77 Interactive\",\"description\":\"Rudy&#039;s Code snippets\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/77interactive.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9\",\"name\":\"Rudy\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/77interactive.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/e336b9aecd39b40691ff8ccfcd68506415072dbe8caffc0485b94a1bc22b774d?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/e336b9aecd39b40691ff8ccfcd68506415072dbe8caffc0485b94a1bc22b774d?s=96&d=mm&r=g\",\"caption\":\"Rudy\"},\"url\":\"http:\/\/77interactive.com\/?author=1\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Linux Configuration Script in Python - 77 Interactive","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"http:\/\/77interactive.com\/?p=245","og_locale":"en_US","og_type":"article","og_title":"Linux Configuration Script in Python - 77 Interactive","og_description":"Verifying Linux Setting in Python The following Python script checks several Linux settings. Results of the check are written to the console. If the results are within the desired ranges and values, the results are displayed in green. If the values are outside of the desired ragnes, results are displayed in red. All results are [&hellip;]","og_url":"http:\/\/77interactive.com\/?p=245","og_site_name":"77 Interactive","article_published_time":"2023-08-23T16:45:09+00:00","article_modified_time":"2023-09-13T14:55:30+00:00","og_image":[{"width":512,"height":512,"url":"http:\/\/77interactive.com\/wp-content\/uploads\/2023\/08\/linux-config.jpeg","type":"image\/jpeg"}],"author":"Rudy","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Rudy","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"http:\/\/77interactive.com\/?p=245#article","isPartOf":{"@id":"http:\/\/77interactive.com\/?p=245"},"author":{"name":"Rudy","@id":"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9"},"headline":"Linux Configuration Script in Python","datePublished":"2023-08-23T16:45:09+00:00","dateModified":"2023-09-13T14:55:30+00:00","mainEntityOfPage":{"@id":"http:\/\/77interactive.com\/?p=245"},"wordCount":72,"image":{"@id":"http:\/\/77interactive.com\/?p=245#primaryimage"},"thumbnailUrl":"http:\/\/77interactive.com\/wp-content\/uploads\/2023\/08\/linux-config.jpeg","keywords":["Linux","mongodb","python"],"articleSection":["mongodb","Python"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"http:\/\/77interactive.com\/?p=245","url":"http:\/\/77interactive.com\/?p=245","name":"Linux Configuration Script in Python - 77 Interactive","isPartOf":{"@id":"http:\/\/77interactive.com\/#website"},"primaryImageOfPage":{"@id":"http:\/\/77interactive.com\/?p=245#primaryimage"},"image":{"@id":"http:\/\/77interactive.com\/?p=245#primaryimage"},"thumbnailUrl":"http:\/\/77interactive.com\/wp-content\/uploads\/2023\/08\/linux-config.jpeg","datePublished":"2023-08-23T16:45:09+00:00","dateModified":"2023-09-13T14:55:30+00:00","author":{"@id":"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9"},"breadcrumb":{"@id":"http:\/\/77interactive.com\/?p=245#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["http:\/\/77interactive.com\/?p=245"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/77interactive.com\/?p=245#primaryimage","url":"http:\/\/77interactive.com\/wp-content\/uploads\/2023\/08\/linux-config.jpeg","contentUrl":"http:\/\/77interactive.com\/wp-content\/uploads\/2023\/08\/linux-config.jpeg","width":512,"height":512,"caption":"Linux Configuration"},{"@type":"BreadcrumbList","@id":"http:\/\/77interactive.com\/?p=245#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/77interactive.com\/"},{"@type":"ListItem","position":2,"name":"Linux Configuration Script in Python"}]},{"@type":"WebSite","@id":"http:\/\/77interactive.com\/#website","url":"http:\/\/77interactive.com\/","name":"77 Interactive","description":"Rudy&#039;s Code snippets","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/77interactive.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9","name":"Rudy","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/77interactive.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/e336b9aecd39b40691ff8ccfcd68506415072dbe8caffc0485b94a1bc22b774d?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/e336b9aecd39b40691ff8ccfcd68506415072dbe8caffc0485b94a1bc22b774d?s=96&d=mm&r=g","caption":"Rudy"},"url":"http:\/\/77interactive.com\/?author=1"}]}},"_links":{"self":[{"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/posts\/245","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=245"}],"version-history":[{"count":0,"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/posts\/245\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/media\/246"}],"wp:attachment":[{"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=245"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=245"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=245"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}