如何使用sudo创建文件并写入?

时间:2014-07-10 18:01:05

标签: ruby ruby-1.9.3 ruby-1.9

我创建了一个bash脚本文件:

#!/bin/bash
default_card=`head -1 /proc/asound/modules`
echo $default_card

if [ ! -e /etc/modprobe.d/sound.blacklist.conf ] ; then
   echo "Default sound card(snd_hda_intel) is not added in black list"
/usr/bin/expect <<delim
exp_internal 0
set timeout 20
spawn sudo sh -c "echo 'blacklist snd_hda_intel' >  /etc/modprobe.d/sound.blacklist.conf"
expect "password for ubuntu:"
send "1234\n"      
expect eof 
delim
else
   echo "Default sound cardis already added in black list";
fi

我正在“/etc/modprobe.d”中创建一个黑名单文件。从“/ etc”创建或删除任何文件都需要sudo访问权限。

我想使用Rake任务在Ruby中实现相同的功能。我创建了这个任务:

desc "Check/creates soundcard blacklist"
task :create_blacklist do
  begin
    if !File.exists?("/etc/modprobe.d/sound.blacklist.conf")
      # code for creating new file and write into it
      ......
      ......
    else
      puts "Sound-card blacklist file is present at /etc/modprobe.d/sound.blacklist.conf"
    end
  rescue Exception => e
    puts "problem creating file #{e.message}"
  end
end

我不知道如何使用sudo创建新文件,并写入。

我使用的是Ruby 1.9.3(没有RVM)。

1 个答案:

答案 0 :(得分:1)

查看https://stackoverflow.com/a/18366155/128421https://stackoverflow.com/a/18398804/128421和&#34; communicating w/ command-line program (OR ruby expect)&#34;了解更多信息。

Ruby的IO类实现了expect但它的功能不是太全面了:

=== Implementation from IO
------------------------------------------------------------------------------
  IO#expect(pattern,timeout=9999999)                  ->  Array
  IO#expect(pattern,timeout=9999999) { |result| ... } ->  nil

------------------------------------------------------------------------------

Reads from the IO until the given pattern matches or the timeout is over.

It returns an array with the read buffer, followed by the matches. If a block
is given, the result is yielded to the block and returns nil.

When called without a block, it waits until the input that matches the given
pattern is obtained from the IO or the time specified as the timeout passes.
An array is returned when the pattern is obtained from the IO. The first
element of the array is the entire string obtained from the IO until the
pattern matches, followed by elements indicating which the pattern which
matched to the anchor in the regular expression.

The optional timeout parameter defines, in seconds, the total time to wait for
the pattern.  If the timeout expires or eof is found, nil is returned or
yielded.  However, the buffer in a timeout session is kept for the next expect
call.  The default timeout is 9999999 seconds.