Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 猫换主人?_Linux_Bash_Ssh - Fatal编程技术网

Linux 猫换主人?

Linux 猫换主人?,linux,bash,ssh,Linux,Bash,Ssh,我必须通过ssh编辑root拥有的文件。我在文件中添加一个条目,保留前9行,并将其余的重新排序到一个临时文件中。我知道>会覆盖文件中的内容(这正是我想要的),但我需要保留根作为文件所有者。我该怎么做?谢谢 #!/bin/bash user="" echo "User:" read user ssh xxxx@xxxx " sed -i '\$a$user' file; (head -n 9 file ; tail -n +10 file | sort) > temp; cat temp &

我必须通过ssh编辑root拥有的文件。我在文件中添加一个条目,保留前9行,并将其余的重新排序到一个临时文件中。我知道>会覆盖文件中的内容(这正是我想要的),但我需要保留根作为文件所有者。我该怎么做?谢谢

#!/bin/bash
user=""
echo "User:"
read user
ssh xxxx@xxxx "
sed -i '\$a$user' file;
(head -n 9 file ; tail -n +10 file | sort) > temp;
cat temp > file;
rm -f temp
"

我已经有一段时间没有在BASH中写过了,但我认为一个起点是

chown root $file // if you have a variable with the file name in 

等式中的另一个变量是谁拥有应用程序cat的所有权?我认为无论谁是正在运行的应用程序的所有者,这就是如何决定其输出的文件的所有权

也许你也可以试试

$ sudo cat temp > file

因为会话将属于根用户,因此输出将属于根用户???

我认为登录的用户不能成为根用户? 那么你最好的办法就是使用dd

dd if=tmpfile of=outfile


当然,在您的tmp文件中执行所有的排序、排序、awking和greping操作。这种用法中的dd相当于>不创建新文件

更改所有者的不是
cat
,而是
sed
。使用
sed-i
时,它会执行以下操作:

mv file file.bak
sed '\$a$user' file.bak > file
rm file.bak
如您所见,这将使用原始文件名创建一个新文件,该文件由创建该文件的用户所有

如果要避免这种情况,请复制原始文件,而不是使用
-i
选项

cp file /tmp/file.$$
sed '\$a$user' /tmp/file.$$ > file
rm /tmp/file.$$
或者您可以将
sed
放入您的管道:

sed '\$a$user' file | head -n 9 file ; tail -n +10 file | sort > temp
cat temp > file
rm temp
如果在xxxx机器上,您登录的xxxx用户对sudo的访问权限没有密码,那么这将更好地工作。您可以在/etc/sudoers文件中输入以下内容:

xxxx ALL=NOPASSWD: ALL

只需将
chown root.root文件
添加到脚本的末尾它不会为我更改所有者?谢谢您的帮助!我使用了echo“$user”>>文件,所以它不会更改所有者。
#!/bin/bash
user=""
echo "User:"
read user
ssh xxxx@xxxx "
sed -i '\$a$user' file;
(head -n 9 file ; tail -n +10 file | sort) > temp;
sudo mv temp file;
sudo chown root file
"
xxxx ALL=NOPASSWD: ALL