0%

如何使用远程命令行登录windows设备并且创建后台任务

使用ssh远程另一台电脑

  • 另一台电脑的22号端口需要可以访问

  • 安装OpenSSH服务器:

    • 打开 设置 (Settings)。
    • 选择 应用 (Apps)。
    • 点击 可选功能 (Optional features)。
    • 选择 添加功能 (Add a feature)。
  • 以管理员身份运行命令行,执行Start-Service sshd

  • 执行Set-Service -Name sshd -StartupType 'Automatic'允许开机自启动

  • 一般需要关闭相关防火墙等

  • 在服务端电脑执行ssh <user>@<ip>

如何在命令行开启一个不依赖于命令行存在的进程

  • 一般的进程在自己依附的命令行被关闭之后就无法继续执行了
    • 会导致使用远程ssh命令行创建的进程在连接断开之后停止运行
  • 需要使用Start-Process命令结合-WindowStyle Hidden参数
  • 一个示例powershell脚本(包括传递命令行参数的部分要写成一个字符串,否则无法传递)
    param (
    [string]$S,
    [string[]]$Arg
    )

    # Conda 环境路径
    $condaEnvPath = "D:\anaconda\envs\torchGPU\python.exe"

    # 获取当前目录
    $currentDirectory = Get-Location


    # 完整脚本路径
    $scriptFullPath = Join-Path -Path $currentDirectory -ChildPath $S

    # 检查脚本是否存在
    if (-Not (Test-Path -Path $scriptFullPath)) {
    Write-Host "Error: Script '$scriptFullPath' does not exist." -ForegroundColor Red
    exit 1
    }
    else {
    Write-Host "Process file '$scriptFullPath'found!"
    Write-Host "Running $condaEnvPath in $currentDirectory"
    }

    # 输出文件路径
    $outputFilePath = Join-Path -Path $currentDirectory -ChildPath "output.txt"
    $errorFilePath = Join-Path -Path $currentDirectory -ChildPath "error.txt"

    # 构建参数字符串
    $argumentsString = "$scriptFullPath " + ($Arg -join ' ')

    Write-Host "'$argumentsString'"

    # 启动进程并重定向输出
    $process = Start-Process -FilePath $condaEnvPath -ArgumentList $argumentsString `
    -RedirectStandardOutput $outputFilePath `
    -RedirectStandardError $errorFilePath `
    -WindowStyle Hidden `
    -PassThru `
    -WorkingDirectory $currentDirectory
    # 输出进程ID
    Write-Host "Process ID: $($process.Id)"

    如何管理进程

  • 查看Get-Process -Id <ID>
  • 停止Stop-Process -Id <ID>