方法一:使用 SFTP 插件(推荐)
1. 安装插件
- 在 VSCode 扩展商店搜索并安装 SFTP(作者:liximomo)
- 或者安装 SFTP/FTP sync 插件
2. 配置 SFTP
步骤:
在项目根目录按
Ctrl+Shift+P,输入
SFTP: Config,选择配置文件
在生成的
sftp.json 文件中配置:
{
"name": "My Server",
"host": "your-server-ip",
"protocol": "sftp",
"port": 22,
"username": "your-username",
"password": "your-password", // 可选,建议使用私钥
"privateKeyPath": "C:/Users/username/.ssh/id_rsa", // Windows路径
// "privateKeyPath": "/Users/username/.ssh/id_rsa", // Mac路径
// "privateKeyPath": "/home/username/.ssh/id_rsa", // Linux路径
"passphrase": "your-passphrase", // 如果私钥有密码
"ignore": [
"**/.vscode/**",
"**/.git/**",
"**/node_modules/**",
"*.log"
],
"remotePath": "/home/username/project", // 服务器上的路径
"uploadOnSave": true, // 保存时自动上传
"syncMode": "update", // 只上传修改的文件
"watcher": { // 监听文件变化
"files": "**/*",
"autoUpload": true,
"autoDelete": true
}
}
3. 使用方式
手动上传单个文件:
- 右键点击文件 →
SFTP: Upload
- 或按
Alt+Shift+S → Upload
上传文件夹:
同步整个项目:
- 右键项目根目录 →
SFTP: Sync Local -> Remote
下载服务器文件:
方法二:使用 Remote - SSH 插件
1. 安装 Remote - SSH 扩展
- 搜索安装官方 Microsoft 的 Remote - SSH
2. 配置连接
点击左侧活动栏的远程资源管理器图标
点击齿轮图标配置 SSH Hosts
在
~/.ssh/config 文件中添加:
Host myserver
HostName your-server-ip
User your-username
Port 22
IdentityFile ~/.ssh/id_rsa
在远程资源管理器中连接服务器
3. 文件操作
连接后:
- 直接拖拽文件到远程窗口
- 右键复制粘贴
- 使用资源管理器直接操作
方法三:命令行方式(备用)
使用 scp 命令:
# 上传单个文件
scp localfile.txt username@server:/remote/path/
# 上传文件夹(递归)
scp -r localfolder username@server:/remote/path/
# 使用指定端口
scp -P 2222 localfile username@server:/path/
使用 sftp 命令:
sftp username@server
put localfile /remote/path/
put -r localfolder /remote/path/
实用技巧
1. 使用密钥认证(更安全)
{
"privateKeyPath": "~/.ssh/id_rsa",
"passphrase": "your-passphrase"
}
2. 排除不需要上传的文件
{
"ignore": [
".git/",
".vscode/",
"node_modules/",
"*.log",
".env"
]
}
3. 配置文件组
{
"profiles": {
"production": {
"host": "prod-server",
"remotePath": "/var/www/prod"
},
"staging": {
"host": "staging-server",
"remotePath": "/var/www/staging"
}
}
}
4. 自动上传配置
{
"uploadOnSave": true,
"watcher": {
"files": "**/*",
"autoUpload": true,
"autoDelete": true
}
}
常见问题解决
1. 连接失败
- 检查服务器 IP 和端口
- 确认防火墙是否开放 22 端口
- 验证用户名和密码/密钥
2. 权限问题
- 确保服务器目录有写入权限
- 可尝试在服务器上:
chmod 755 /path/to/directory
3. 中文乱码
{
"encoding": "utf8"
}
4. 排除 .gitignore 文件
{
"ignore": ".gitignore"
}
推荐组合
开发时:使用 SFTP 插件的
uploadOnSave 功能
批量上传:使用
Sync Local -> Remote
复杂操作:使用 Remote - SSH 直接编辑远程文件
选择哪种方式取决于你的具体需求:
- 简单上传:SFTP 插件
- 完整远程开发:Remote - SSH
- 自动化部署:可以配合部署脚本