【问题标题】:how to run multiple fedora commands in python如何在python中运行多个fedora命令
【发布时间】:2021-06-29 15:06:46
【问题描述】:

所以我试图让 Python 运行多个命令来安装程序并启用 SSH 来设置我的 Linux 计算机。我会输入所有这些,但我会在更多设备上这样做,所以我想为什么不输入 Python 脚本,但到目前为止说起来容易做起来难。我对此进行了大量研究,但找不到类似的东西。

这就是我目前所得到的。

--import subprocess
--SSH = "systemctl enable sshd"
--payload = "nmap" # it'll be one of a few I'll be installing

--subprocess.call(["sudo", "yum", "install", "-y", payload])
--subprocess.call(["sudo", SSH])

第一部分完美运行。它要求我输入密码,它会更新并安装 nmap。但是由于某种原因,命令“systemctl enable sshd”似乎总是把它扔掉。我知道该命令有效,因为我只需将其输入,它本身就可以正常工作,但由于某种原因,它无法通过此脚本工作。我也用过subprocess.run。我在这里错过了什么?

这是我得到的错误:

--sudo: systemctl start sshd: command not found

【问题讨论】:

  • 对于像这样的人,我当然会建议改写一个 bash 脚本

标签: python linux command-line fedora


【解决方案1】:

你想要的是 Ansible。

Ansible 使用 SSH 连接到机器列表并执行配置任务。任务用 YAML 描述,可读且可扩展。您可以拥有剧本和临时命令。例如,临时安装包将是

ansible -i inventory.file -m yum -a "name=payload state=present"

在剧本中看起来像安装并启用 openssh-server

---
- hosts: all                                      # Single or group of hosts from inventory file
  become: yes                                     # Become sudo
  tasks:                                          # List of tasks
  - name: Install ssh-server                      # Description free text
    yum:                                          # Module name
      name: openssh-server                        # Name of the package
      state: present                              # State " state: absent will uninstall the package"  
  - name: Start and enable service                # Description of the task free text
    service:                                      # Service
      name: sshd                                  # Name of the service
      state: started                              # Started or Stopped
      enabled: yes                                # Start the service on boot
                     
  - name: Edit config file sshd_config            # Description of the task
    lineinfile:                                   # Name of the module
      path: /etc/sshd/sshd_config                 # Which file to edit
      regex: ^(# *)?PasswordAuthentication        # Which line to edit
      line: PasswordAuthentication no             # Whit what to change it
    

Ansible 有很棒的文档 https://docs.ansible.com/ 几天后你就会跟上进度。

最好的问候。

【讨论】:

  • 太棒了,谢谢你,我会调查一下,让你知道我发现了什么!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 2019-08-14
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
相关资源
最近更新 更多